to-json-schema

Convert JS object to JSON Schema

to-json-schema

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

Install

npm install to-json-schema

Example usage

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

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

const schema = toJsonSchema(objToBeConverted);

schemagenerated 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)

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

  • value: requiredAny javascript value
  • options: optional options object

Options

Common options

Possible option values

required(true|falsedefault is false) specify trueto 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, valueparams.

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 requiredfor the schema items if there is common option requiredset 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|tupledefault is all)

alloption 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
      }
    }
  }
}
*/

firstoption 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"
  }
}
*/

uniformoption 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'
*/

tupleoption 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: falsewhich 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 objparam.

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 aand bfrom 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, objparams.

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 objobject.

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:

  • stringto be converted into JSON schema
  • default functionthat normally generates the schema. This function receives only stringto 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|falsedefault 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: 'obama@whitehouse.gov'
};
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"
    }
  }
}
*/

HomePage

https://github.com/ruzicka/to-json-schema#readme

Repository

https+https://github.com/ruzicka/to-json-schema


上一篇:proxymise
下一篇:zamza

相关推荐

  • 高效遍历匹配Json数据,避免嵌套循环

    工作中经常会遇到这样的需求: 1.购物车列表中勾选某些,点击任意一项,前往详情页,再返回购物车依旧需要呈现勾选状态 2.勾选人员后,前往别的页面,再次返回,人员依旧程勾选状态 3.等等.......

    2 年前
  • 面试题|手写JSON解析器

    这周的 Cassidoo 的每周简讯有这么一个面试题:: 写一个函数,这个函数接收一个正确的 JSON 字符串并将其转化为一个对象(或字典,映射等,这取决于你选择的语言)。

    3 个月前
  • 隐藏某些价值观输出stringify() JSON。

    Evan CarrollNilesh(https://stackoverflow.com/users/124486/evancarroll)提出了一个问题:Hide certain values in...

    2 年前
  • 随着Nodejs JSON对象响应(转换对象数组JSON字符串)

    Rudolf Olahclimboid(https://stackoverflow.com/users/9903/rudolfolah)提出了一个问题:Responding with a JSON o...

    2 年前
  • 铬sendrequest错误:列表的循环结构转换到JSON

    SomeKittensSkizit(https://stackoverflow.com/users/1216976/somekittens)提出了一个问题:Chrome sendrequest err...

    2 年前
  • 重新认识 package.json

    前言 🤔 在每个项目的根目录下面,一般都会有一个 package.json 文件,其定义了运行项目所需要的各种依赖和项目的配置信息(如名称、版本、许可证等元数据)。

    4 天前
  • 重新认识 package.json

    前言 🤔 在每个项目的根目录下面,一般都会有一个 package.json 文件,其定义了运行项目所需要的各种依赖和项目的配置信息(如名称、版本、许可证等元数据)。

    20 天前
  • 遍历json获得数据的几种方法小结

    Json在Web开发的用处非常广泛,作为数据传递的载体,如何解析Json返回的数据是非常常用的。下面介绍下四种解析Json的方式: Part 1 Part 2 解释: countryO...

    3 年前
  • 通过jsonp获取json数据实现AJAX跨域请求

    AJAX()是用于创建快速动态网页的一种技术,它在不重新加载整个页面的情况下,与服务器交换数据并更新部分网页,ajax 使用对象在后台与服务器交换数据,XMLHttpRequest 是 AJAX 的基...

    3 年前
  • 通过JavaScript创建JSON对象动态(无级连字符串)

    Waqar Alamgirohadinho(https://stackoverflow.com/users/457124/waqaralamgir)提出了一个问题:Create JSON object...

    2 年前

官方社区

扫码加入 JavaScript 社区