JSON模式引用文档中的另一个元素

Bal*_*des 6 json jsonschema

Is there a way to express reference to another element in the same JSON document using JSON schema? The title might be a bit confusing, but i'm not looking for the "$ref" attribute, which references another type, but I'm curious, if there is a way, to reference another element in the document using a specified field. I know this is possible to enforce using xsd for xml documents, not sure about JSON.

I want to do something like this:

{
  "people": [
    { "id": "1", "name": "A" },
    { "id": "2", "name": "B" },
    { "id": "3", "name": "C" }
  ],
  "chosenOne": "1" // I want the schema to enforce a person ID here
}
Run Code Online (Sandbox Code Playgroud)

I have been looking at the schema definition of v4: http://json-schema.org/draft-04/schema but didn't find anything, that looks like what I'm trying to do. Did I just miss it?

Bat*_*via 5

您想要的是在架构所描述的对象中描述一个引用 ($ref)。

有点像这样

{
    "people": []
    "chosenOne": { $ref: "#1"}
}
Run Code Online (Sandbox Code Playgroud)

(或者,如果您想要 Id 的值,则可能是一个指针(http://json-spec.readthedocs.org/en/latest/pointer.html

我知道没有直接的方法可以做到这一点,但您可以使用模式或 oneof 属性来强制它成为正确的值。有点像这样

"properties": {
    "chosenOne"
         "type": "string",
         "oneOf": ["1","2","3"]
         ]
     },
}
Run Code Online (Sandbox Code Playgroud)

同样,您可以强制该属性的值成为参考模式。也就是说,由于没有引用值类型(http://www.tutorialspoint.com/json/json_data_types.htm)只有数字或字符串,因此您无法保证该值的含义。您可以保证 if 遵循某种参考模式。

如果您需要的不仅仅是 json 架构可以提供的内容,您可能需要查看 odata 例如。OData 有一些额外的东西,因此您可以描述一个 entitySet,然后为该集合定义一个导航属性。然而,它确实迫使您遵循 odata 结构,因此您不像使用常规 json 模式那样自由。

  • 这同时非常有趣和奇怪。谢谢 :) (2认同)