2

我正在编写一个可以从文件中读取 JSON 数据的软件。该文件包含“person” - 一个对象,其值为对象数组。我打算使用 JSON 模式验证库来验证内容,而不是自己编写代码。什么是符合代表以下数据的 JSON Schema Draf-4 的正确模式?

{
   "person" : [
      {
         "name" : "aaa",
         "age"  : 10
      },
      {
         "name" : "ddd",
         "age"  : 11
      },
      {
         "name" : "ccc",
         "age"  : 12
      }
   ]
}

下面给出了写下的模式。我不确定它是否正确或是否有任何其他形式?

{
   "person" : {
      "type" : "object",
      "properties" : {
         "type" : "array",
         "items" : {
            "type" : "object",
            "properties" : {
               "name" : {"type" : "string"},
               "age" : {"type" : "integer"}
            }
         }
      }
   }
}
4

1 回答 1

1

您实际上只有一行放在错误的位置,但那一行破坏了整个架构。“人”是对象的属性,因此必须在properties关键字下。通过将“人”放在顶部,JSON Schema 将其解释为关键字而不是属性名称。由于没有person关键字,JSON Schema 会忽略它以及它下面的所有内容。因此,它与针对空模式进行验证相同,它对{}JSON 文档可以包含的内容没有任何限制。任何有效的 JSON 对于空模式都是有效的。

{
   "type" : "object",
   "properties" : {
      "person" : {
         "type" : "array",
         "items" {
            "type" : "object",
            "properties" : {
               "name" : {"type" : "string"}
               "age" : {"type" : "integer"}
            }
         }
      }
   }
}

顺便说一句,有几种在线 JSON Schema 测试工具可以帮助您制作模式。这是我的转到http://jsonschemalint.com/draft4/#

此外,这里有一个很棒的 JSON Schema 参考,它也可能对您有所帮助:https ://spacetelescope.github.io/understanding-json-schema/

于 2016-07-27T23:55:00.590 回答