I've never used JSON before so I'm not familiar with its syntax.
At the moment I have multiple arrays containing different pieces of data.
I would like to create one JSON object, that contains the multiple arrays each with several pieces of data.
E.g.
An object called cars, containing multiple arrays each for a different make of car. In each array would be the model of car along with some other types of data e.g. number of doors (doesn't really matter its just a fictional example.)
It would be greatly appreciated if someone explained the syntax with an example.
To convert two arrays into a JSON object, we have used the forEach() method to iterate over the first array. we have used the index to get the element from the second array. On every iteration forEach() method will assign the key-value pair to a JSON object.
JSON arrays can be of multiple data types. JSON array can store string , number , boolean , object or other array inside JSON array. In JSON array, values must be separated by comma. Arrays in JSON are almost the same as arrays in JavaScript.
The JSON data is an object (basically an associative array). Indexed arrays use square brackets, [0,1,2] , while associative arrays use curly braces, {x:1,y:2,z:3} . Any of the data within the outermost object can be either type of array, but the outermost object itself has to use curly braces.
On the outermost level, a JSON object starts with a {
and end with a }
.
Sample data:
{ "cars": { "Nissan": [ {"model":"Sentra", "doors":4}, {"model":"Maxima", "doors":4}, {"model":"Skyline", "doors":2} ], "Ford": [ {"model":"Taurus", "doors":4}, {"model":"Escort", "doors":4} ] } }
If the JSON is assigned to a variable called data, then accessing it would be like the following:
data.cars['Nissan'][0].model // Sentra data.cars['Nissan'][1].model // Maxima data.cars['Nissan'][2].doors // 2 for (var make in data.cars) { for (var i = 0; i < data.cars[make].length; i++) { var model = data.cars[make][i].model; var doors = data.cars[make][i].doors; alert(make + ', ' + model + ', ' + doors); } }
Another approach (using an associative array for car models rather than an indexed array):
{ "cars": { "Nissan": { "Sentra": {"doors":4, "transmission":"automatic"}, "Maxima": {"doors":4, "transmission":"automatic"} }, "Ford": { "Taurus": {"doors":4, "transmission":"automatic"}, "Escort": {"doors":4, "transmission":"automatic"} } } } data.cars['Nissan']['Sentra'].doors // 4 data.cars['Nissan']['Maxima'].doors // 4 data.cars['Nissan']['Maxima'].transmission // automatic for (var make in data.cars) { for (var model in data.cars[make]) { var doors = data.cars[make][model].doors; alert(make + ', ' + model + ', ' + doors); } }
Edit:
Correction: A JSON object starts with {
and ends with }
, but it's also valid to have a JSON array (on the outermost level), that starts with [
and ends with ]
.
Also, significant syntax errors in the original JSON data have been corrected: All key names in a JSON object must be in double quotes, and all string values in a JSON object or a JSON array must be in double quotes as well.
See:
A good book I'm reading: Professional JavaScript for Web Developers by Nicholas C. Zakas 3rd Edition has the following information regarding JSON Syntax:
"JSON Syntax allows the representation of three types of values".
Regarding the one you're interested in, Arrays it says:
"Arrays are represented in JSON using array literal notation from JavaScript. For example, this is an array in JavaScript:
var values = [25, "hi", true];
You can represent this same array in JSON using a similar syntax:
[25, "hi", true]
Note the absence of a variable or a semicolon. Arrays and objects can be used together to represent more complex collections of data, such as:
{ "books": [ { "title": "Professional JavaScript", "authors": [ "Nicholas C. Zakas" ], "edition": 3, "year": 2011 }, { "title": "Professional JavaScript", "authors": [ "Nicholas C.Zakas" ], "edition": 2, "year": 2009 }, { "title": "Professional Ajax", "authors": [ "Nicholas C. Zakas", "Jeremy McPeak", "Joe Fawcett" ], "edition": 2, "year": 2008 } ] }
This Array contains a number of objects representing books, Each object has several keys, one of which is "authors", which is another array. Objects and arrays are typically top-level parts of a JSON data structure (even though this is not required) and can be used to create a large number of data structures."
To serialize (convert) a JavaScript object into a JSON string you can use the JSON object stringify() method. For the example from Mark Linus answer:
var cars = [{ color: 'gray', model: '1', nOfDoors: 4 }, { color: 'yellow', model: '2', nOfDoors: 4 }];
cars is now a JavaScript object. To convert it into a JSON object you could do:
var jsonCars = JSON.stringify(cars);
Which yields:
"[{"color":"gray","model":"1","nOfDoors":4},{"color":"yellow","model":"2","nOfDoors":4}]"
To do the opposite, convert a JSON object into a JavaScript object (this is called parsing), you would use the parse() method. Search for those terms if you need more information... or get the book, it has many examples.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With