JSON string, starts with array - json

I have the following strings:
[{"result": True}]
[{"result": False}, {"info": "Describing error}]
Does this strings are correct JSON strings? Or I should use smth. like this:
{"result": False, "info": "error"}

The first one is a valid JSON string (an array with one element). The second is missing a quote, but after fixing that it is valid.

First one would resolve to an Array with one Dictionary
Second one would resolve to an Array with two Dictionaries (BTW you are missing the end quote on your string)
Third one would resolve to a Dictionary.
It will all depend on how you will want/need to consume the JSON response. All three of these can be consumed, just depends on your situation.

Related

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)
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
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)
A thing for json validation
https://www.npmjs.com/package/json-validation
https://davidwalsh.name/json-validation.

Is this valid JSON? Does root of a JSON stream/file have to be a single object or array?

Is the following valid JSON?
["start", 1234]
["open", 97]
I read the official standard twice and I wasn't able to find anything that said that this isn't valid JSON.
Interesting question. Couldn't help but research a bit. RFC-7159 explicitly refers to ECMA-404, which says:
A JSON value can be an object, array, number, string, true, false, or null
So basically, ECMA-404 tells us that a JSON value can be either of the above, but only a single one of them. Given your example:
["start", 1234]
["open", 97]
That'd not be considered valid JSON together, at it is not an array, but two arrays, and therefore two JSON values and not one.

Is a plain string valid JSON? [duplicate]

This question already has answers here:
Is this simple string considered valid JSON?
(5 answers)
Closed 5 years ago.
Is a plain string valid JSON or does there have to be an object?
For example:
"morpheus"
versus:
{
"name": "morpheus"
}
It is valid in Javascript.
You might get confused at first trying to test this:
JSON.parse("bob");
This would fail with the error: "Unexpected token b". However, that's the equivalent of passing just plain bob as the text in the response, not "bob". If you add the quotes:
JSON.parse('"bob"')
You get the simple string "bob" back as you should.
Important
This answer once said No, the first character of the JSON must be a { or a [.
At the time I wrote that, I was testing it with Python. In Python (2.7.x at least), json.loads("a") gives an error, which means that a plain string is not valid JSON there.
It has been rightfully pointed out by others that it cannot be said that a plain string is not valid JSON. See this question for a more appropriate answer.
At this time all I can say is that it depends on your environment. In javascript it may be valid, in python it may not be, etc, etc.
JSON stands for JavaScript Object Notation
Here is a quote from the official site
JSON is built on two structures:
A collection of name/value pairs. In various languages, this is
realized as an object, record, struct, dictionary, hash table, keyed
list, or associative array. An ordered list of values. In most
languages, this is realized as an array, vector, list, or sequence.
These are universal data structures. Virtually all modern programming
languages support them in one form or another. It makes sense that a
data format that is interchangeable with programming languages also be
based on these structures.
In JSON, they take on these forms:
An object is an unordered set of name/value pairs. An object begins
with { (left brace) and ends with } (right brace). Each name is
followed by : (colon) and the name/value pairs are separated by ,
(comma).
Take note of the text I bolded.
Because of that, and JSON being JS Object Notation, it is implied that a JSON representation of a name:value pair must always be in the form of
{
"name": "value"
}
Note that you can also make the 'root object' a list
[
{
"name1": "value1"
},
{
"name2": "value2"
}
]
This basically means that the JSON contains more than one object.
As Sunny R Gupta pointed out, this is also valid JSON
[
"this",
"is",
"valid"
]
Note that this works because the strings are not in the form "name":"value" but just strings. Taking that into consideration valid options for your example would be
{
"name": "Morpheus"
}
or
[
"morpheus"
]
The first character of the JSON must be a { or a [
UPDATE: 2018:
It has been 4 years since I originally answered this question. Back then plain strings in quotes were not valid JSON. As of today, it is being accepted as a valid JSON.
The following is kept for people to see what the error used to be earlier:
Parsing a simple string gives:
Parse error on line 1:
"morpheus"
^
Expecting '{', '['
indicating that it needs to be an object or an array.
TIP: To validate JSON strings and see what works and what does not, try using http://jsonlint.com

What kind of Json structure is this? 4-dimensional array?

{"filters":
[
[
"Color",
[
[
"Blue",
629,
"t12-15=blue"
],
[
"Green",
279,
"t12-15=green"
]
]
],
[
"Style",
[
[
"Contemporary / Modern",
331,
"t6-11=contemporary+modern"
],
[
"Transitional",
260,
"t6-11=transitional"
],
]
]
]}
This looks like a 4 dimensional array to me, but when I tried to use ServiceStack.Text.JsonSerializer to deserialize it, I do not get the expected result.
Looks like the values "Color" and "Style" are not in an array per se. What kind of Json structure is this?
It is indeed an array of arrays of arrays of arrays wrapped in an object. It's quite horrible, but I don't see why JsonSerializer would choke on it.
What kind of structure? Irregular, really. An object containing a field which contains an array which contains arrays in which the first item is a string, and the second item is an array containing two items which are arrays of string, number and string items .... phew!
Nothing wrong with this at all!
To me it just looks like an object containing an array of arrays that goes 4 levels deep, so its an object with one field that is a 4D array. if you want to get the 4D array you'll need to get the filters field from the json object returned
It looks approximately like that Jackson might produce when you ask it to use arrays instead of objects to represent maps.
Style and Color are just the first index of the arrays that they're in. This is almost certainly NOT what was intended. If anything Style should probably be the label (object) for the next Array rather than its sibling, no? The obvious follow-up question is who/what is producing this JSON, and who/what is consuming it... as bmarguiles asks... what *is your expectation here, given that the JSON is syntactically valid, if it's not doing what you expect... what do you expect?
Edit based on your comment:
well... since you seem to be able to rely on the fact that these are all nested arrays and that the label that you're looking for is going to be the 0th index of whatever array, you can just recurse into the array looking for that label and then treating the array that is at the 1st index with the assumption that it will contain the data you expect. It's ugly, but it looks like it will work (so long as the service that generates this doesn't change). C# has a JSON deserializer james.newtonking.com/pages/json-net.aspx . You should just use that.

Is a value on its own a valid JSON string?

In a JSON API, is it valid to return single values such as 123, "somestring" or null?
I read the JSON spec, which states that:
JSON is built on two structures:
A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.
An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.
but I'm not clear if this means that only objects and arrays are valid JSON, or if values on their own are valid too (i.e. will be parsed correctly by any compliant parser).
Any idea?
No, it's not valid. Check this out if you want to experiment with anything.
The two structures are as follows:
Some kind of key-value pair:
{
"key": "value"
}
or an array
['value', 'value']
or any combination of the two
[{"key":"value"}, "value", ["a", "list", {"another":['list']}]]
However, the values on their own (numbers, strings, booleans, etc., are not valid on their own.
Is 123 a collection of name/value pairs? No, it is not.
Is 123 an ordered list of values? No, it is not.
Thus, 123 is not a valid JSON string.
Edit: As gdoron suggested, you could use a JSON parser (e.g. here) to test your single value.