npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

gen-json-schema

v0.2.7

Published

Convert JS object to JSON Schema

Downloads

5

Readme

npm version Test Suite Coverage Status

gen-json-schema

Converts javascript objects (and other types) to corresponding JSON schema

This is a fork of ruzicka/to-json-schema with a fix for issue #24. Since the original is no longer maintained, I plan to maintain this package, resolve oustanding issues and modernize it with ESM and types

Install

npm install gen-json-schema

Example usage

const toJsonSchema = require('gen-json-schema');

const objToBeConverted = {
  name: 'David',
  rank: 7,
  born: '1990-04-05T15:09:56.704Z',
  luckyNumbers: [7, 77, 5]
};

const schema = toJsonSchema(objToBeConverted);

schema generated from above code will look like this:

{
  "type": "object",
  "properties": {
    "name": {
      "type": "string"
    },
    "rank": {
      "type": "integer"
    },
    "born": {
      "type": "string",
      "format": "date-time"
    },
    "luckyNumbers": {
      "type": "array",
      "items": {
        "type": "integer"
      }
    }
  }
}

toJsonSchema(value, options)

gen-json-schema exports function that converts most javascript values to JSON schema. Such a schema can be used to further validation of similar objects/values

  • value: required Any javascript value
  • options: optional options object

Options

Common options

Possible option values

required (true|false default is false) specify true to make all properties required.

const schema = toJsonSchema(33, {required: false});
/*
{
  "type": "integer"
}
*/
const schema = toJsonSchema(33, {required: true});
/*
{
  "type": "integer",
  "required": true
}
*/

postProcessFnc (function)

parameters:

  • type (string) - JSON schema type of the value
  • schema (object) - Generated JSON schema
  • value - (any) - input value
  • defaultFunc (function) - standard function that is used to post-process generated schema. Takes the type, schema, value params.

By providing postProcessFnc, you can modify or replace generated schema. This function will be called recursively for all the properties and sub-properties and array items from leaves to the root. If you want to preserve default functionality, don't forget to call defaultFunc which is currently responsible for setting required for the schema items if there is common option required set tu true.

Following example is showing configuration options leading to all integer values to be automatically required

const options = {
  postProcessFnc: (type, schema, value, defaultFunc) =>
    (type === 'integer') ? {...schema, required: true} : defaultFunc(type, schema, value),
}

const instance = {
  a: 1,
  b: 'str',
}

const schema = toJsonSchema(instance, options);
/*
{
  type: 'object',
  properties: {
    a: {type: 'integer', required: true},
    b: {type: 'string'},
  },
}*/

Arrays options

arrays.mode (all|first|uniform|tuple default is all)

all option causes parser to go through all array items, finding the most compatible yet most descriptive schema possible.

Array items are all of compatible type:

const arr = [33, 44, 55];
const schema = toJsonSchema(arr, {arrays: {mode: 'all'}});
/*
{
  "type": "array",
  "items": {
    "type": "integer"
  }
}
*/

Items' types are incompatible. Type is omitted in schema to be able to validate input object:

const arr = [33, 'str', 55];
const schema = toJsonSchema(arr, {arrays: {mode: 'all'}});
/* 
{
  "type": "array"
}
*/

Incompatible in sub-item. Schema still describes object properties

const arr = [
  {name: 'john', grades: [1, 2, 3]},
  {name: 'david', grades: ['a', 'b', 'c']}
];
const schema = toJsonSchema(arr, {arrays: {mode: 'all'}});
/*
{
  "type": "array",
  "items": {
    "type": "object",
    "properties": {
      "name": {
        "type": "string"
      },
      "grades": {
        "type": "array" // due to incompatible array items' types, `items` field is omitted
      }
    }
  }
}
*/

first option takes only first item in the array into account. If performance is a concern, you may consider this option.

const arr = ['str', 11, 30];
const schema = toJsonSchema(arr, {arrays: {mode: 'first'}});
/* Other than first array item is ignored
{
  "type": "array",
  "items": {
    "type": "string"
  }
}
*/

uniform option requires all items in array to have same structure (to convert to the same schema). If not, error is thrown.

const arr = ['str', 11, 30];
const schema = toJsonSchema(arr, {arrays: {mode: 'uniform'}});
/*
 Above code will throw 'Error: Invalid schema, incompatible array items'
*/

tuple option generates a tuple array (array of objects) from arrays.

const arr = ['str', 11, 30];
const schema = toJsonSchema(arr, {arrays: {mode: 'tuple'}});
/*
{
  "type": "array",
  "items": [
    {
      "type": "string"
    },
    {
      "type": "integer"
    },
    {
      "type": "integer"
    }
  ]
}
*/

Objects options

objects.additionalProperties (boolean, default true)

if set to false, all object schemas will include JSON schema property additionalProperties: false which makes generated schema to perevent any extra properties.

const options = {
  objects: {additionalProperties: false},
}
const obj = {
  a: {
    c: 1,
    d: 1,
  },
  b: 'str',
}
const schema = toJsonSchema(obj, options);
/*
{
  type: 'object',
  properties: {
    a: {
      type: 'object',
      properties: {
        c: {type: 'integer'},
        d: {type: 'integer'},
      },
      additionalProperties: false,
    },
    b: {type: 'string'},
  },
  additionalProperties: false,
}
*/

objects.preProcessFnc (function)

parameters:

  • obj - (object) - input object value that is supposed to be converted into JSON schema
  • defaultFunc (function) - standard function that is used to generate schema from object. Takes just the obj param.

By providing custom function you will be able to modify any object value (including nested ones) and pre-process it before it gets converted into schema or modify generated schema or do the schema conversion entirely by yourself.

Custom function from example bellow ignores all properties other than a and b from input object:

const options = {
  objects: {
    preProcessFnc: (obj, defaultFnc) => defaultFnc({a: obj.a, b: obj.b})
  }
};
const obj = {a: 1, b: 2, c: 3};
const schema = toJsonSchema(obj, options);
/*
{
  "type": "object",
  "properties": {
    "a": {
      "type": "integer"
    },
    "b": {
      "type": "integer",
    }
  }
}
*/

objects.postProcessFnc (function)

parameters:

  • schema (object) - Generated JSON schema
  • obj - (object) - input value
  • defaultFunc (function) - standard function that is used to post-process generated schema. Takes the schema, obj params.

By providing postProcessFnc, you can modify or replace generated schema. This function will be called recursively for all the properties and sub-properties and array items from leaves to the root of the obj object.

Custom objects.postProcessFnc makes properties required on parent type level:

const options = {
  objects: {
    postProcessFnc: (schema, obj, defaultFnc) => ({...defaultFnc(schema, obj), required: Object.getOwnPropertyNames(obj)})
  }
};
const obj = {a: 1, b: 'str'};
const schema = toJsonSchema(obj, options);
/*
{
  type: 'object',
  properties: {
    a: {type: 'integer'},
    b: {type: 'string'},
  }
  required: ['a', 'b']
}
*/

strings options

strings.preProcessFnc (function)

By providing custom function you will be able to modify any string value (including nested ones) and pre-process it before it gets converted to schema, modify generated schema or do the schema conversion entirely by yourself.

Provided function will receive two parameters:

  • string to be converted into JSON schema
  • default function that normally generates the schema. This function receives only string to be converted to JSON schema

Custom function from example bellow converts any string of object containing string to JSON schema and if string's content is 'date' than sets the format property to 'date':

const options = {
  strings: {
    preProcessFnc: (value, defaultFnc) => {
      const schema = defaultFnc(value);
      if (value === 'date') {
        schema.format = 'date';
      }
      return schema;
    },
  },
}
const schema = toJsonSchema('date', options);
/*
{
  "type": "string",
  "format": "date"
}
*/

strings.detectFormat (true|false default id true)

When set to true format of the strings values may be detected based on it's content.

These JSON schema string formats can be detected:

  • date-time
  • date
  • time
  • utc-millisec
  • color
  • style
  • phone
  • uri
  • email
  • ip-address
  • ipv6
const obj = {
  a: '2012-07-08T16:41:41.532Z',
  b: '+31 42 123 4567',
  c: 'http://www.google.com/',
  d: '[email protected]'
};
const schema = toJsonSchema(obj, {strings: {detectFormat: true}});
/*
{
  "type": "object",
  "properties": {
    "a": {
      "type": "string",
      "format": "date-time"
    },
    "b": {
      "type": "string",
      "format": "phone"
    },
    "c": {
      "type": "string",
      "format": "uri"
    },
    "d": {
      "type": "string",
      "format": "email"
    }
  }
}
*/