Harry Harry - 1 year ago 56
JSON Question

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.


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. Thanks.

Answer Source

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}
        "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   // 4

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


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.