How do I make a JSON object with multiple arrays?

Json

Json Problem Overview


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.

Json Solutions


Solution 1 - Json

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:

Solution 2 - Json

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.

Solution 3 - Json

Another example:

[  
[  
    {  
        "@id":1,
        "deviceId":1,
        "typeOfDevice":"1",
        "state":"1",
        "assigned":true
    },
    {  
        "@id":2,
        "deviceId":3,
        "typeOfDevice":"3",
        "state":"Excelent",
        "assigned":true
    },
    {  
        "@id":3,
        "deviceId":4,
        "typeOfDevice":"júuna",
        "state":"Excelent",
        "assigned":true
    },
    {  
        "@id":4,
        "deviceId":5,
        "typeOfDevice":"nffjnff",
        "state":"Regular",
        "assigned":true
    },
    {  
        "@id":5,
        "deviceId":6,
        "typeOfDevice":"44",
        "state":"Excelent",
        "assigned":true
    },
    {  
        "@id":6,
        "deviceId":7,
        "typeOfDevice":"rr",
        "state":"Excelent",
        "assigned":true
    },
    {  
        "@id":7,
        "deviceId":8,
        "typeOfDevice":"j",
        "state":"Excelent",
        "assigned":true
    },
    {  
        "@id":8,
        "deviceId":9,
        "typeOfDevice":"55",
        "state":"Excelent",
        "assigned":true
    },
    {  
        "@id":9,
        "deviceId":10,
        "typeOfDevice":"5",
        "state":"Excelent",
        "assigned":true
    },
    {  
        "@id":10,
        "deviceId":11,
        "typeOfDevice":"5",
        "state":"Excelent",
        "assigned":true
    }
],
1
]

Read the array's

$.each(data[0], function(i, item) {
         data[0][i].deviceId + data[0][i].typeOfDevice  + data[0][i].state +  data[0][i].assigned 
    });

Use http://www.jsoneditoronline.org/ to understand the JSON code better

Solution 4 - Json

var cars = [
    manufacturer: [
        {
            color: 'gray',
            model: '1',
            nOfDoors: 4
        },
        {
            color: 'yellow',
            model: '2',
            nOfDoors: 4
        }
    ]
]

Solution 5 - Json

Using the below method pass any value which is an array:

Use:
<dependency>
    <groupId>com.jayway.jsonpath</groupId>
    <artifactId>json-path</artifactId>
    <version>2.5.0</version>
</dependency>


Input parameter: URL, like 
Example: "$node.[any int value of array].anyKeyWhichInArray"
Example: "$.cars.Nissan.[0].model"





    public String getAnyValueFromResponseBody(String jsonBody, String url) {
        String value = "";
        try {
          value = JsonPath.read(jsonBody, url).toString();
          System.out.println(value);
        } catch (Exception var6) {
          System.error.println("unable to parse "+url);
        }
        return value;
      }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionHarryView Question on Stackoverflow
Solution 1 - JsonMatt CoughlinView Answer on Stackoverflow
Solution 2 - JsonObedView Answer on Stackoverflow
Solution 3 - JsonJason GlezView Answer on Stackoverflow
Solution 4 - JsonDanilo ValenteView Answer on Stackoverflow
Solution 5 - JsonAnkit GuptaView Answer on Stackoverflow