2016-07-27 82 views
0

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

{ 
    "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"} 
      } 
     } 
     } 
    } 
} 

回答

1

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

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

顺便说一下,有几个在线的JSON模式测试工具可以帮助您在制定模式时提供帮助。这一个是我转到http://jsonschemalint.com/draft4/#

而且,这里是一个伟大的JSON模式的参考,可以帮助你出去,以及:https://spacetelescope.github.io/understanding-json-schema/

相关问题