node.js - 如何生成 JSON 模式?
问题描述
我想从 json 对象生成模式。
var GenerateSchema = require('generate-schema')
var schema = GenerateSchema.json(request.body);
请求正文
{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [
102,
0.5
]
},
"properties": {
"prop0": "value0"
}
},
{
"type": "Feature",
"geometry": {
"type": "LineString",
"coordinates": [
[
102,
0
],
[
103,
1
],
[
104,
0
],
[
105,
1
]
]
},
"properties": {
"prop0": "value0",
"prop1": 0
}
},
{
"type": "Feature",
"geometry": {
"type": "Polygon",
"coordinates": [
[
[
100,
0
],
[
101,
0
],
[
101,
1
],
[
100,
1
],
[
100,
0
]
]
]
},
"properties": {
"prop0": "value0",
"prop1": {
"this": "that"
}
}
}
]
}
从 request.body 生成的模式
{
"$id": "http://json-schema.org/draft-04/schema#",
"$schema": "http://json-schema.org/draft-04/schema#",
"title": "Product",
"type": "object",
"properties": {
"type": {
"type": "string"
},
"features": {
"type": "array",
"items": {
"type": "object",
"properties": {
"type": {
"type": "string"
},
"geometry": {
"type": "object",
"properties": {
"type": {
"type": "string"
},
"coordinates": {
"type": "array",
"items": {
"oneOf": [
{
"type": "number"
},
{
"type": "number"
},
{
"type": "number"
},
{
"type": "number"
},
{
"type": "number"
}
],
"type": "array"
}
}
}
},
"properties": {
"type": "object",
"properties": {
"prop0": {
"type": "string"
},
"prop1": {
"type": "object",
"properties": {
"this": {
"type": "string"
}
}
}
}
}
},
"required": [
"type",
"geometry",
"properties"
]
}
}
}
}
使用 Ajv 进行模式验证
[
{
keyword: 'type',
dataPath: '.features[0].geometry.coordinates[0]',
schemaPath: '#/properties/features/items/properties/geometry/properties/coordinates/items/type',
params: { type: 'array' },
message: 'should be array'
}
]
为什么 Ajv 检测到问题?
解决方案
我用 QuickType 库找到了答案
推荐阅读
- java - 我可以在构造函数中使用枚举常量的名称吗?
- flutter - Dart gRPC 文件中的时间戳导入无效
- android - 当应用程序将要关闭时如何运行代码
- python - 你可以在 Python 中执行内联导入吗?
- mongodb - 使用来自外部的凭据在 mongodb 容器中运行命令
- rust - 这个“可能未初始化”的编译器错误是误报吗?[锈病 1.51.0]
- amazon-web-services - KeyError:Lambda 日志中的“s3”
- bash - 比较两个文件的内容(差异)
- css - 如果未使用变量,有没有办法使用默认属性值?SCSS
- spring - 使用新的 Spring Boot 应用程序进行 CAS 身份验证