JsonSchema转JSON
Posted Jay_帅小伙
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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;
;
以上是关于JsonSchema转JSON的主要内容,如果未能解决你的问题,请参考以下文章