英文:
json schema validator how to get extra field
问题
{
"type": "object",
"properties": {
"firstName": {
"type": "string"
},
"lastName": {
"type": "string"
},
"age": {
"type": "integer"
}
}
}
{
"firstName": "John",
"lastName": "Doe",
"age": 21,
"abcd": "how to get this field",
"efg": "and this field"
}
我想要获取在 JSON 模式中未定义的额外字段,就像 "abcd" 和 "efg"。输出应类似于:["abcd", "efg"]
<details>
<summary>英文:</summary>
I define a json shema like this
```json
{
"type": "object",
"properties": {
"firstName": {
"type": "string",
},
"lastName": {
"type": "string",
},
"age": {
"type": "integer"
}
}
}
and here is my json
{
"firstName": "John",
"lastName": "Doe",
"age": 21,
"abcd": "how to get this field",
"efg": "and this field"
}
I want to get the extra field which is not defined in json schema, just like "abcd" and "efg".
Output like this: ["abcd","efg"]
答案1
得分: 2
如果您想添加一个随机属性(例如abcd),而不是通用的(firstName、lastName、age),最好在您的JSON模式中使用一个映射对象,您可以填入任何键值对(例如abcd - "how to get this field")。
{
"$schema": "http://json-schema.org/draft-04/schema#",
"type": "object",
"properties": {
"firstName": {
"type": "string"
},
"lastName": {
"type": "string"
},
"age": {
"type": "integer"
},
"attributes": {"$ref": "#/definitions/StringMap"}
},
"required": [
"firstName",
"lastName",
"age"
],
"definitions": {
"StringMap": {
"type": "object",
"additionalProperties": {"type": "string"}
}
}
}
(代码部分已省略)
英文:
If you want to add a random property (like abcd) instead of generic( firstName, lastname, age), it would be better if you have a map object in your JSON schema, where you can fill in any key, value pairs ( like abcd - "how to get this field").
{
"$schema": "http://json-schema.org/draft-04/schema#",
"type": "object",
"properties": {
"firstName": {
"type": "string"
},
"lastName": {
"type": "string"
},
"age": {
"type": "integer"
},
"attributes": {"$ref": "#/definitions/StringMap"}
},
"required": [
"firstName",
"lastName",
"age"
],
"definitions": {
"StringMap": {
"type": "object",
"additionalProperties": {"type": "string"}
}
}
}
答案2
得分: 0
我认为你正在询问如何将JSON架构更改以在用户添加额外属性时拒绝输入。在这种情况下,你可以将additionalProperties设置为false。
{
"type": "object",
"properties": {
"firstName": {
"type": "string"
},
"lastName": {
"type": "string"
},
"age": {
"type": "integer"
}
},
"additionalProperties": false
}
我对你在GitHub上的原始问题感到困惑。
https://github.com/networknt/json-schema-validator/issues/322
英文:
I think you are asking how the JSON schema is changed to reject the input if extra properties are added by the user. In that case, you can set additionalProperties to false.
{
"type": "object",
"properties": {
"firstName": {
"type": "string",
},
"lastName": {
"type": "string",
},
"age": {
"type": "integer"
}
},
"additionalProperties": false
}
I was confused with your original question in the GitHub.
https://github.com/networknt/json-schema-validator/issues/322
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论