在JSON模式中定义键值对的正确方法是什么 [英] What is the Correct way to define key-value pairs in json schema

查看:100
本文介绍了在JSON模式中定义键值对的正确方法是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在json模式中定义键值对对象(正确"的方式)?

How do i define key value pairs object in json schema (the "correct" way) ?

我想定义这个:

"id" : 99,
_info : {
    "name" : "somename",
    "href" : "someUrl"
}

以下两项是否正确?

1)

{
    "type": "object",
    "name": "MyObj",
    "properties": {
        "id": {
            "type": "integer"
        },
        "_info": {
            "type": "array",
            "items": {
                "type": "object"
                "properties": {
                    "key": {
                        "type": "string",
                        "description": "key"
                    },
                    "value": {
                        "type": "string",
                        "description": "the value"
                    }
                }
            }
        }
    }
}

2)

{
    "type": "object",
    "name": "MyObj",
    "properties": {
        "id": {
            "type": "integer",
        "_info": {
            "type": "object",
            "additionalProperties": {
                "type": "string",
                "description": "string values"
            }
        }
    }
}

实现此目标的正确方法是什么?人们会知道序列化/反序列化后的模式是什么,对象看起来像什么?

What is the correct way to get this accomplished and people will know what the schema is and the object will look like when serialized/deserialized?

推荐答案

在JSON中,对象已经是键值对的集合.您不需要任何特殊的定义即可:

In JSON an object is already a collection of key-value pairs. You don't need anything special in order to define it:

{
    "_info":{"type":"object"}
}

您可以在此处添加约束.

From here you can add constraints.

  • 如果您知道键的名称,则将它们添加到属性"中
  • 如果您知道所有可能的键,请将"additionalProperties"设置为false
  • 如果要限制可能的键名,请使用"patternProperties".

更新2019/09/10

如注释中所建议,如果要将所有属性限制为字符串类型,则可以通过以下方式做到这一点:

As suggested in comments, if you want to restrict all properties to be of type string, you may do it this way:

{
  "title": "Force every property to have a string value",
  "$schema": "http://json-schema.org/draft-07/schema#",
  "type": "object",
  "additionalProperties": {"type": "string"}
}

这篇关于在JSON模式中定义键值对的正确方法是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆