
Security News
MCP Community Begins Work on Official MCP Metaregistry
The MCP community is launching an official registry to standardize AI tool discovery and let agents dynamically find and install MCP servers.
@peculiar/json-schema
Advanced tools
This package uses ES2015 decorators to simplify JSON schema creation and use
The @peculiar/json-schema package is a powerful tool for working with JSON schemas in JavaScript. It allows for serialization and deserialization of JavaScript objects based on JSON Schema definitions. This package is particularly useful for ensuring data integrity and for validating data structures in applications that heavily utilize JSON.
Serialization
This feature allows you to serialize JavaScript objects into JSON strings based on a defined JSON schema. It ensures that the serialized data adheres to the specified schema structure.
const { JsonParser } = require('@peculiar/json-schema');
const schema = {
type: 'object',
properties: {
name: { type: 'string' },
age: { type: 'number' }
}
};
const person = { name: 'John', age: 30 };
const serialized = JsonParser.serialize(person, schema);
console.log(serialized);
Deserialization
This feature enables the deserialization of JSON strings into JavaScript objects, validating against a JSON schema. It is useful for parsing and validating incoming JSON data to ensure it meets expected formats and constraints.
const { JsonParser } = require('@peculiar/json-schema');
const schema = {
type: 'object',
properties: {
name: { type: 'string' },
age: { type: 'number', minimum: 18 }
}
};
const jsonData = '{"name":"John","age":30}';
const deserialized = JsonParser.parse(jsonData, schema);
console.log(deserialized);
Ajv is a popular JSON schema validator that offers fast validation of JSON objects against schemas. It is more focused on validation rather than serialization/deserialization but is highly optimized for performance.
Joi is a powerful schema description language and data validator for JavaScript. Unlike @peculiar/json-schema, Joi does not strictly use JSON Schema standards but provides a rich set of features for building and validating complex data structures.
This package uses ES2015 decorators to simplify JSON schema creation and use.
JSON (JavaScript Object Notation) is a lightweight data-interchange format that was designed to be easy for humans to read and write but in practice, it is minefield when it machines need to parse it.
While the use of schemas can help with this problem their use can be complicated. When using json-schema
this is addressed by using decorators to make both serialization and parsing of XML possible via a simple class that handles the schemas for you.
This is important because validating input data before its use is important to do because all input data is evil. Using a schema helps you handle this data safely.
Installation is handled via npm
:
$ npm install @peculiar/json-schema
Creating a schema:
import { JsonParser, JsonSerializer, JsonProp, JsonPropTypes, IJsonConverter } from "@peculiar/json-schema";
// custom data converter
const JsonBase64UrlConverter: IJsonConverter<Uint8Array, string> = {
fromJSON: (value: string) => base64UrlToBuffer(value),
toJSON: (value: Uint8Array) => bufferToBase64Url(value),
};
class EcPublicKey {
@JsonProp({ name: "kty" })
keyType = "EC";
@JsonProp({ name: "crv" })
namedCurve = "";
@JsonProp({ converter: JsonBase64UrlConverter })
x = new Uint8Array(0);
@JsonProp({ converter: JsonBase64UrlConverter })
y = new Uint8Array(0);
@JsonProp({ name: "ext", type: JsonPropTypes.Boolean, optional: true })
extractable = false;
@JsonProp({ name: "key_ops", type: JsonPropTypes.String, repeated: true, optional: true })
usages: string[] = [];
}
const json = `{
"kty": "EC",
"crv": "P-256",
"x": "zCQ5BPHPCLZYgdpo1n-x_90P2Ij52d53YVwTh3ZdiMo",
"y": "pDfQTUx0-OiZc5ZuKMcA7v2Q7ZPKsQwzB58bft0JTko",
"ext": true
}`;
const ecPubKey = JsonParser.parse(json, { targetSchema: EcPublicKey });
console.log(ecPubKey);
ecPubKey.usages.push("verify");
const jsonText = JsonSerializer.serialize(ecPubKey, undefined, undefined, 2);
console.log(jsonText);
// Output
//
// EcPublicKey {keyType: "EC", namedCurve: "P-256", x: Uint8Array(32), y: Uint8Array(32), extractable: true, …}
//
// {
// "kty": "EC",
// "crv": "P-256",
// "x": "zCQ5BPHPCLZYgdpo1n+x/90P2Ij52d53YVwTh3ZdiMo=",
// "y": "pDfQTUx0+OiZc5ZuKMcA7v2Q7ZPKsQwzB58bft0JTko=",
// "ext": true,
// "key_ops": [
// "verify"
// ]
// }
Extending a Schema:
class BaseObject {
@JsonProp({ name: "i" })
public id = 0;
}
class Word extends BaseObject {
@JsonProp({ name: "t" })
public text = "";
}
class Person extends BaseObject {
@JsonProp({ name: "n" })
public name = 0;
@JsonProp({ name: "w", repeated: true, type: Word })
public words = [];
}
const json = `{
"i":1,
"n":"Bob",
"w":[
{"i":2,"t":"hello"},
{"i":3,"t":"world"}
]
}`;
const person = JsonParser.parse(json, { targetSchema: Person });
console.log(person);
const word = new Word();
word.id = 4;
word.text = "!!!";
const jsonText = JsonSerializer.serialize(person, undefined, undefined, 2);
console.log(jsonText);
// Output
//
// Person {id: 1, name: "Bob", words: [Word {id: 2, text: "hello"}, Word {id: 3, text: "world"}]}
// {
// "i": 1,
// "n": "Bob",
// "w": [
// {
// "i": 2,
// "t": "hello"
// },
// {
// "i": 3,
// "t": "world"
// },
// {
// "i": 4,
// "t": "!!!"
// }
// ]
// }
Use index.d.ts file
FAQs
This package uses ES2015 decorators to simplify JSON schema creation and use
The npm package @peculiar/json-schema receives a total of 2,653,214 weekly downloads. As such, @peculiar/json-schema popularity was classified as popular.
We found that @peculiar/json-schema demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 6 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
The MCP community is launching an official registry to standardize AI tool discovery and let agents dynamically find and install MCP servers.
Research
Security News
Socket uncovers an npm Trojan stealing crypto wallets and BullX credentials via obfuscated code and Telegram exfiltration.
Research
Security News
Malicious npm packages posing as developer tools target macOS Cursor IDE users, stealing credentials and modifying files to gain persistent backdoor access.