94

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.

Philip Kirkbride
  • 21,381
  • 38
  • 125
  • 225
Harry
  • 1,120
  • 1
  • 12
  • 15
  • 2
    You don't work with JSON directly, except in very rare circumstances. You work with native data structures, then use a library to convert that structure to a JSON string. – Marc B Jun 25 '12 at 21:51

6 Answers6

186

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:

Asa Stallard
  • 322
  • 1
  • 14
Matt Coughlin
  • 18,666
  • 3
  • 46
  • 59
  • Just to clarify: is this an object? Does it need [] brackets? – Harry Jun 25 '12 at 22:03
  • 5
    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. – Matt Coughlin Jun 25 '12 at 22:10
  • And how would I loop through the towns in this: http://pastebin.com/qyQ2Y9sn so that I could access the lat and lng. – Harry Jun 25 '12 at 22:21
  • 1
    `for (var town in markers.towns) { alert(markers.towns[town].lat) }` – Matt Coughlin Jun 25 '12 at 22:24
  • 1
    Sure, no problem :) I added some examples of iterating through the JSON data in both examples above. – Matt Coughlin Jun 25 '12 at 22:32
  • How would you access the make of car in the first example? – Harry Jun 25 '12 at 23:52
  • If you mean the model (since the make is accessed the same in both examples), there's no direct way to access the model, which is why I added the second example. In the first one, you have to iterate through through the data until you find the model you're looking for. – Matt Coughlin Jun 26 '12 at 00:18
  • See the notes at the end of the answer above. There were significant mistakes that have been corrected. – Matt Coughlin Jun 26 '12 at 12:52
  • Two mistakes: Put "towns" in double quotes, and remove the last comma (there should only be a comma between elements, not at the end of the last element). – Matt Coughlin Jun 26 '12 at 13:19
  • Now my code doesn't work, do I still reference to it in the same way? `var town in markers.towns` and `markers.towns[town].lat`. – Harry Jun 26 '12 at 13:28
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/13054/discussion-between-matt-coughlin-and-harry) – Matt Coughlin Jun 26 '12 at 13:29
  • @MattCoughlin is datatype of data here JSONObject ? – Ragini Sep 22 '17 at 13:12
  • There is a typo in the second code example: `data.cars['Nissan'][2].doors` should be `data.cars['Nissan'][1].doors`. I cannot edit the answer because I need to edit at least 6 characters – Luca Dec 13 '17 at 10:02
  • The correction sentence at the bottom solved my issue ty. all i needed was an array of elements, eg [1,2,3] – Andrew Feb 22 '18 at 14:56
24

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.

John F
  • 39
  • 1
  • 5
Obed
  • 400
  • 1
  • 9
  • In the above example "edition" & "year" should be in quotes - https://jsonlint.co.uk/ won't validate otherwise – rexall Jul 27 '18 at 13:33
3

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

Jason Glez
  • 1,254
  • 1
  • 16
  • 16
2
var cars = [
    manufacturer: [
        {
            color: 'gray',
            model: '1',
            nOfDoors: 4
        },
        {
            color: 'yellow',
            model: '2',
            nOfDoors: 4
        }
    ]
]
Danilo Valente
  • 11,270
  • 8
  • 53
  • 67
  • What about having a car manufacturer array inside the object? so `cars` > `manufacturer` > `model, color, doors`. (arrays within arrays within an object) – Harry Jun 25 '12 at 21:51
0

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
Albina
  • 1,901
  • 3
  • 7
  • 19
-3
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;
      }
Ankit Gupta
  • 776
  • 5
  • 12