Is it valid for JSON data structure to vary between a list and a boolean

江枫思渺然 提交于 2019-12-24 00:17:47

问题


The json data structure for jstree is define in https://github.com/vakata/jstree, here is an example

[ { "text" : "Root node", "children" : [ "Child node 1", "Child node 2" ] } ]

Notably it says

The children key can be used to add children to the branch, it should be an array

However later on in section Populating the tree using AJAX and lazy loading nodes it shows to use set children to false to indicate when a child has not be processed

[{
  "id":1,"text":"Root node","children":[
    {"id":2,"text":"Child node 1","children":true},
    {"id":3,"text":"Child node 2"}
  ]
}]

So here we see children used as both as an array and as a boolean

I am using jstree as an example because this is where I encountered the issue, but my question is really a general json question. My question is this, is it valid JSON for the same element in json to be two different types (an array and a boolean)


回答1:


Structure wise, both are valid JSON packets. This is okay, as JSON is somewhat less stricter than XML(with a XSD or a DTD). As per: https://www.w3schools.com/js/js_json_objects.asp,

JSON objects are surrounded by curly braces {}.
JSON objects are written in key/value pairs.
Keys must be strings, and values must be a valid JSON data type (string, number, object, array, boolean or null).
Keys and values are separated by a colon.
Each key/value pair is separated by a comma.

Having said that, if the sender is allowed to send such JSONs, only caveat is that server side will have to handle this discrepancy upon receiving such different packets. This is a bad-looking-contract, and hence server might need to do extra work to manage it. Server side handling of such incoming JSON packets can become tricky.

See: How do I create JSON data structure when element can be different types in for use by

You could validate whether a JSON is okay or not at https://jsonlint.com/

See more about JSON in this answer: https://stackoverflow.com/a/4862511/945214




回答2:


It is valid Json. JSON RFC 8259 defines a general syntax but it contains nothing that would allow a tool to identify that two equally named entries are meant to describe the same conceptual thing. The need to have a criteria to check two JSON structures for instance equality has been one motivation to create something like Json Schema.

I also think it is not too unusual for javascript to provide this kind of mixed data. Sometimes it might help to explicitly convert the javascript object to JSON. Like in JSON.stringify(testObject)




回答3:


A thing for json validation https://www.npmjs.com/package/json-validation https://davidwalsh.name/json-validation.



来源:https://stackoverflow.com/questions/48540346/is-it-valid-for-json-data-structure-to-vary-between-a-list-and-a-boolean

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!