JsonSchema转JSON

先安装所需要的依赖

yarn add underscore json-schema-faker

使用

test(JsonsSchema格式)是假数据
const _ = require('underscore');
const mwapi = require('../utils/schema2json');
 @Get('/schema2json')
  async schema2json() {
    const test:any = {
      schema: {
        $schema: 'http://json-schema.org/draft-04/schema#',
        type: 'object',
        properties: {
          code: { type: 'string', mock: { mock: '555' } },
          arr: {
            type: 'object',
            properties: {
              item1: { type: 'string', mock: { mock: 'i1' } },
              item2: { type: 'string', mock: { mock: '@string' } },
            },
            description: '数组',
            required: ['item1', 'item2'],
          },
        },
        required: ['arr'],
      }
    };
    let schema = test.schema;
    let required = test?.required;
    console.log('mwapi',mwapi)
    let res = mwapi.schemaToJson(schema, {
      alwaysFakeOptionals: _.isUndefined(required) ? true : required,
    });
    console.log('***********',res)
  /**res=
  
	{
		"arr": {
			"item1": "i1",
			"item2": "DjTwg^"
		},
		"code": "5556"
	}
*/
    return res
  }

schema2json.js

const jsf = require('json-schema-faker');
//这里执行mock字段 使用mockjs去执行
jsf.extend('mock', function () {
  return {
    mock: function (xx) {
      return Mock.mock(xx);
    }
  };
});
  /** 如果不加上面一段res会响应如下
	{
		"arr": {
			"item1": "fugiat sit incididunt magna",
			"item2": "enim minim aute"
		},
		"code": "quis eiusmod"
	}
	*/


const defaultOptions = {
  failOnInvalidTypes: false,
  failOnInvalidFormat: false
};
exports.schemaToJson = function (schema, options = {}) {
  Object.assign(options, defaultOptions);

  jsf.option(options);
  let result;
  try {
    result = jsf(schema);
  } catch (err) {
    result = err.message;
  }
  jsf.option(defaultOptions);
  return result;
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用Python中的jsonschema库来实现jsonschema对象到其他格式的换。以下是将jsonschema对象换为JSON字符串和Python字典的示例代码: ```python import json from jsonschema import Draft7Validator # 定义一个jsonschema对象 schema = { "type": "object", "properties": { "name": {"type": "string"}, "age": {"type": "integer", "minimum": 0} }, "required": ["name", "age"] } # 将jsonschema对象换为JSON字符串 schema_json = json.dumps(schema) # 将jsonschema对象换为Python字典 schema_dict = dict(schema) # 使用jsonschema库进行验证 validator = Draft7Validator(schema) instance = {"name": "Tom", "age": 25} errors = list(validator.iter_errors(instance)) print(schema_json) print(schema_dict) print(errors) ``` 输出结果: ``` {"type": "object", "properties": {"name": {"type": "string"}, "age": {"type": "integer", "minimum": 0}}, "required": ["name", "age"]} {'type': 'object', 'properties': {'name': {'type': 'string'}, 'age': {'type': 'integer', 'minimum': 0}}, 'required': ['name', 'age']} [] ``` 在上面的示例中,我们首先定义了一个jsonschema对象。然后使用json.dumps()函数将其换为JSON字符串,使用dict()函数将其换为Python字典。 最后,我们使用jsonschema库中的Draft7Validator类来验证一个实例是否符合定义的jsonschema。在此示例中,我们创建了一个实例变量,然后使用iter_errors()函数进行验证。如果实例不符合jsonschema的定义,则会返回一个错误列表。在这个示例中,实例满足jsonschema的定义,因此错误列表为空。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值