Search code examples
jsonjstree

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


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)


Solution

  • 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