且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

列表和布尔值之间的JSON数据结构是否有效?

更新时间:2023-11-29 18:58:40

从结构上讲,它们都是有效的JSON数据包.没关系,因为JSON比XML(使用XSD或DTD)严格一些.按照: 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.

已经说过,如果允许发送方发送此类JSON,则仅需说明的是,服务器端在接收到此类不同的数据包时将必须处理此差异.这是一个看起来很糟糕的合同,因此服务器可能需要做一些额外的工作来管理它.服务器端处理此类传入的JSON数据包可能会变得很棘手.

请参阅: https://jsonlint.com/

上验证JSON是否正确>

在此答案中了解有关JSON的更多信息: https://***.com/a/4862511/945214 >

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)

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://***.com/a/4862511/945214