Harry
Harry

Reputation: 1150

How do I make a JSON object with multiple arrays?

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.

Upvotes: 97

Views: 705580

Answers (6)

Albina
Albina

Reputation: 1985

I know this is an old question but I would like to add another JSON example along with Java code.

Example JSON:

{
  "cars": [
      {
        "model": "Nissan",
        "code": "1",
        "id": "12",
        "properties": {"color": "red", "doors": "4", "engine": "best", "price": "500", "is_electric": "false"}
      },
      {
        "model": "Tesla",
        "code": "2",
        "id": "13",
        "properties": {"color": "grey", "doors": "4", "engine": "best", "price": "800", "is_electric": "true"}
      },
      {
        "model": "Kia",
        "code": "3",
        "id": "14",
        "properties": {"color": "green", "doors": "4", "engine": "diesel", "price": "900", "is_electric": "false"}
      }
  ]
}
  • "cars" represents a JSON array
  • Each JSON object inside of "cars" array describes a car using "properties" JSON object and other fields.
    • For sure, each car may have some unique "id", "code" and "model" name.
    • Additionally, the "properties" object helps to describe another set of car characteristics. It consists of "color", "doors", "engine", "price", and "is_electric" fields.

Java code:

This code manipulates the JSON object with the help of org.json library.

  1. jsonObject stores the whole JSON string.
  2. Then we retrieve the highest level object "cars" into jsonArray variable.
  3. Using for-loop we iterate over the JSON array and print each car's JSON data.
public static void main(String[] args) throws InterruptedException {
    String carsJson = "insert_your_json"; //TODO

    JSONObject jsonObject = new JSONObject(carsJson);
    JSONArray jsonArray = jsonObject.getJSONArray("cars");
    int length = jsonArray.length();
    for (int i = 0; i < length; i++) {
        printData(jsonArray.getJSONObject(i));
    }
}

private static void printData(JSONObject jsonObject) {
    String message = "Id: %s\nModel: %s\nCode: %s\n" +
            "Properties:\n\tcolor: %s\n\tdoors: %s\n\tengine: %s\n\tprice: %s\n\tis_electric: %s\n\n";
    JSONObject properties = jsonObject.getJSONObject("properties");

    System.out.printf(message, 
            jsonObject.get("id"), jsonObject.get("model"), jsonObject.get("code"),
            properties.get("color"), properties.get("doors"), properties.get("engine"), 
            properties.get("price"), properties.get("is_electric"));
}

Output:

Id: 12
Model: Nissan
Code: 1
Properties:
    color: red
    doors: 4
    engine: best
    price: 500
    is_electric: false

Id: 13
Model: Tesla
Code: 2
Properties:
    color: grey
    doors: 4
    engine: best
    price: 800
    is_electric: true

Id: 14
Model: Kia
Code: 3
Properties:
    color: green
    doors: 4
    engine: diesel
    price: 900
    is_electric: false

Upvotes: 1

Ankit Gupta
Ankit Gupta

Reputation: 786

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;
      }

Upvotes: -3

Obed
Obed

Reputation: 400

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.

Upvotes: 24

Matt Coughlin
Matt Coughlin

Reputation: 18906

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:

Upvotes: 188

Jason Glez
Jason Glez

Reputation: 1512

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

Upvotes: 4

Danilo Valente
Danilo Valente

Reputation: 11352

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

Upvotes: 2

Related Questions