What is the general format for a json file? - json

What is the general format for a JSON file?
Is it a dictionary with 1 key whose value is a list of dictionaries (with each dictionary corresponding to a row)?

The general format of json is a key-value pair where each value may contain either a value, an array of values, or another set of key-value pairs.
As described on json.org:
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.
For example:
{"employees":[
{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith"},
{"firstName":"Peter", "lastName":"Jones"}
]}

Related

Does JSON syntax allow duplicate values?

Is this valid JSON?
{
"a" : [
"x",
"x"
]
}
http://jsonlint.com/ says yes.
http://www.json.org/ doesn't say anything about it being forbidden, but does say:
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.
An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.
"An ordered list of values" suggests duplicates are therefore valid. Is this correct? Is there anything more explicit? Are there any JSON implementation which don't allow duplicate values?
(Here's the related question about duplicate keys.)
That is valid JSON. What is not allowed is having duplicate keys, such as:
{
"a": 1,
"a": 2
}
Also, by "ordered" I believe it refers to the fact that values have a predefined, well established order, not that they are sorted in any way :)

Is {0:{"id":1,...},{"id:2,....}} a other reprensation of a JSON list like [{"id":1,...},{"id:2,....}]

I have a little dilema. I have a backend/Frontend Application that comunicates with a JSON based REST Api.
The backend is written in PHP(Symfony/jmsserializer) and the Frontend in Dart
The communication between these two has a little Problem.
For most List Data the backend responds with a JSON like
[{"id":1,...},{"id:2,....}]
But for some it responds with
{"0":{"id":1,...}, "1":{"id:2,....}}
Now my Question is should the backend respond with the later at all or only with the first?
Problem
You usually have a list of objects. You sometimes get an object with sub-objects as properties.
Underlying issue
JS/JSON-Lists are ordered from 0 upwards which means that if you have PHP-Array which does not respect this rule json_encode will output a JS/JSON-Object instead using the numeric indices as keys.
PHP-Arrays are ordered maps which have more features that the JSON-Lists. Whenever you're using those extra features you won't be able to translate directly into JSON-Lists without loosing some information (ordering, keys, skipped indices, etc.).
PHP-Arrays and JSON-Objects on the other hand are more ore less equivalent in terms of features and can be correctly translated between each other without any loss of information.
Occurence
This happens if you have an initial PHP-Array of values which respects the JS/JSON-List rules but the keys in the list of objects are modified somehow. For example if you have a custom indexing order {"3":{}, "0":{}, "1":{}, "2":{}} or if you have (any) keys that are strings (ie. not numeric).
This always happens if you want to use the numeric id of the object as the numeric index of the list {"123":{"id": 123, "name": "obj"}} even if the numeric ids are in ascending order... so long as they are not starting from 0 upwards it's not a json-list it's a json-object.
Specific case
So my guess is that the PHP code in the backend is doing something like fetching a list of objects but its modifying something about it like inserting them by (string) keys into the array, inserting them in a specific order, removing some of them.
Resolution
The backend can easily fix this by using array_values($listOfObjects) before using json_encode which will reindex the entire list by numeric indices of ascending value.
Arrays and dictionaries are two separate types in JSON ("array" and "object" respectively), but PHP combines this functionality in a single array type.
PHP's json_encode deals with this as follows: an array that only contains numeric keys ($array = ['cat', 'dog']) is serialized as JSON array, an associative array that contains non-numeric keys ($array = ['cat' => 'meow', 'dog' => 'woof']) is serialized as JSON object, including the array's keys in the output.
If you end up with an associative array in PHP, but want to serialize it as a plain array in JSON, just use this to convert it to a numerical array before JSON encoding it: $array = array_values($array);

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.

JSON members order in ActionScript 3.0

I'm using built-in functionality to create JSON string in Flash app.
Here example of my source code
objStr = JSON.stringify(
{
version:"1.0",
skin:"white",
palette:{dataColor:"#0397d6",negativeDataColor:"#d40000",toolbarColor:"#056393"}
});
I have a problem. Every time I've started my app (not executing createJSON function), I have different member order in JSON string as result.
For example:
{"version":"1.0","palette":{"negativeDataColor":"#d40000","dataColor":"#0397d6","toolbarColor":"#056393"},"skin":"white"}
or
{"palette":{"negativeDataColor":"#d40000","toolbarColor":"#056393","dataColor":"#0397d6"},"version":"1.0","skin":"white"}
How can I fix it.
JSON objects are unordered, see JSON.org:
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 object is an unordered set of name/value pairs
An ordered list of values. In most languages, this is realized as an
array, vector, list, or sequence. An array is an ordered collection of values.
Order really doesn't matter since you should be retrieving the values by the key rather than iterating over them.

Can JSON start with "["?

From what I can read on json.org, all JSON strings should start with { (curly brace), and [ characters (square brackets) represent an array element in JSON.
I use the json4j library, and I got an input that starts with [, so I didn't think this was valid JSON. I looked briefly at the JSON schema, but I couldn't really find it stated that a JSON file cannot start with [, or that it can only start with {.
JSON can be either an array or an object. Specifically off of json.org:
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.
It then goes on to describe the two structures as:
Note that the starting and ending characters are curly brackets and square brackets respectively.
Edit
And from here: http://www.ietf.org/rfc/rfc4627.txt
A JSON text is a sequence of tokens.
The set of tokens includes six
structural characters, strings,
numbers, and three literal names.
A JSON text is a serialized object or array.
Update (2014)
As of March 2014, there is a new JSON RFC (7159) that modifies the definition slightly (see pages 4/5).
The definition per RFC 4627 was: JSON-text = object / array
This has been changed in RFC 7159 to: JSON-text = ws value ws
Where ws represents whitespace and value is defined as follows:
A JSON value MUST be an object, array, number, or string, or one of
the following three literal names:
false null true
So, the answer to the question is still yes, JSON text can start with a square bracket (i.e. an array). But in addition to objects and arrays, it can now also be a number, string or the values false, null or true.
Also, this has changed from my previous RFC 4627 quote (emphasis added):
A JSON text is a sequence of tokens. The set of tokens includes six
structural characters, strings, numbers, and three literal names.
A JSON text is a serialized value. Note that certain previous
specifications of JSON constrained a JSON text to be an object or an
array. Implementations that generate only objects or arrays where a
JSON text is called for will be interoperable in the sense that all
implementations will accept these as conforming JSON texts.
If the string you are parsing begins with a left brace ([) you can use JSONArray.parse to get back a JSONArray object and then you can use get(i) where i is an index from 0 through the returned JSONArray's size()-1.
import java.io.IOException;
import com.ibm.json.java.JSONArray;
import com.ibm.json.java.JSONObject;
public class BookListTest {
public static void main(String[] args) {
String jsonBookList = "{\"book_list\":{\"book\":[{\"title\":\"title 1\"},{\"title\":\"title 2\"}]}}";
Object book_list;
try {
book_list = JSONObject.parse(jsonBookList);
System.out.println(book_list);
Object bookList = JSONObject.parse(book_list.toString()).get("book_list");
System.out.println(bookList);
Object books = JSONObject.parse(bookList.toString()).get("book");
System.out.println(books);
JSONArray bookArray = JSONArray.parse(books.toString());
for (Object book : bookArray) {
System.out.println(book);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Which produced output like:
{"book_list":{"book":[{"title":"title 1"},{"title":"title 2"}]}}
{"book":[{"title":"title 1"},{"title":"title 2"}]}
[{"title":"title 1"}, {"title":"title 2"}]
{"title":"title 1"}
{"title":"title 2"}
Note: if you attempted to call JSONObject.parse(books.toString()); you would get the error you encountered:
java.io.IOException: Expecting '{' on line 1, column 2 instead, obtained token: 'Token: ['
JSON.ORG WEBSITE SAYS ....
https://www.json.org/
The site clearly states the following:
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:
OBJECT:
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).
{string: value, string: value}
ARRAY:
An array is an ordered collection of values. An array begins with [ (left bracket) and ends with ] (right bracket). Values are separated by , (comma).
[value, value, value ….]
VALUE:
A value can be a string in double quotes, or a number, or true or false or null, or an object or an array. These structures can be nested.
STRING:
A string is a sequence of zero or more Unicode characters, wrapped in double quotes, using backslash escapes. A character is represented as a single character string. A string is very much like a C or Java string.
NUMBER:
A number is very much like a C or Java number, except that the octal and hexadecimal formats are not used.
ABOUT WHITESPACE:
Whitespace can be inserted between any pair of tokens. Excepting a few encoding details, that completely describes the language.
Short answer is YES
In a .json file you can put Numbers (even just 10), Strings (even just "hello"), Booleans (true, false), Null (even just null), arrays and objects.
https://www.json.org/json-en.html
Using just Numbers, Strings, Booleans and Null are not logical because in .jon files we use more complicated structured data like arrays and object (mostly mix nested versions).
Below you can find a sample JSON data with array of object and start with "["
https://jsonplaceholder.typicode.com/posts