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:

  • JSON specification
  • JSONLint - The JSON validator
Answer from Matt Coughlin on Stack Overflow
Top answer
1 of 6
188

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:

  • JSON specification
  • JSONLint - The JSON validator
2 of 6
23

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.

🌐
W3Schools
w3schools.com › js › js_json_arrays.asp
JSON Arrays
In JSON, array values must be of type string, number, object, array, boolean or null.
🌐
Adobe
opensource.adobe.com › Spry › samples › data_region › JSONDataSetSample.html
JSON Data Set Sample
Example 5 - The "path" constructor option and JSON Array with objects as elements. Example 6 - The "subPaths" constructor option with a single path. Example 7 - The "subPaths" constructor option with multiple paths.
🌐
UiPath Community
forum.uipath.com › help › studio
JSON Array with multiple json objects and json arrays - Studio - UiPath Community Forum
September 27, 2021 - hello, I made an API call and I got a json response. I deserialized the json response, so that I have a json object. Now I want to extract some information from the object, but I have not managed to do it. Here is my json response: { “results”: [ { “group”: { “mediaType”: “chat”, “queueId”: “7a982920-3a-4083-8315-db0f5fec6c44” }, “data”: [ { “interval”: “2021-08-16T00:00:00.000Z/2021-08-22T00:00:00.000Z”, “metrics”: [ { “metric”: “tAcw”, “stats”: { “max”: 800000, “min”: 6000, ...
🌐
RestfulAPI
restfulapi.net › home › json › json array
JSON Array - Multi-dimensional Array in JSON
November 4, 2023 - A simple for loop to iterate over a multi-dimensional array in JSON. for (i in siteInfo .users) { for (j in siteInfo.users[i]) { x = siteInfo.users[i][j]; console.log(x); } } ... A fun-loving family man, passionate about computers and problem-solving, with over 15 years of experience in Java and related technologies.
🌐
Reddit
reddit.com › r/learnpython › multiple objects in json file
r/learnpython on Reddit: Multiple objects in JSON file
February 5, 2020 -

Hey, i am new to programming and I am trying to decode thousands of JSON files.
Usually there is one object in each JSON file, but for some reason a lot of my files have multiple JSON objects. Some have up to 5 objects.

{
	"testNumber": "test200",
	"device": {
		"deviceID": 4000008

	},
	"user": {
		"userID": "4121412"
	}
}
{
	"testNumber": "test201",
	"device": {
		"deviceID": 4000009

	},
	"user": {
		"userID": "4121232"
	}
}

My code gives me the error: json.decoder.JSONDecodeError: Extra data: line 2 column 1
Because of that I am using except ValueError but I would like to get the data out of these JSON files.

import json
import os

test_dir = r'C:\Users\path\path'
for file in os.listdir(test_dir):
    if 'testNumber' in file:
        try: 
            data = json.load(open(test_dir + '\\' + file, 'r'))  
            print("valid")
        except ValueError: 
               print("Decoding JSON has failed")

Since json.loads and json.load don't work: is there any other way open the JSON file so that I can try to split the content in 2 objects?

Find elsewhere
🌐
Quora
quora.com › Can-JSON-contain-multiple-objects
Can JSON contain multiple objects? - Quora
Answer (1 of 2): The file is invalid if it contains more than one JSON object. When you try to load and parse a JSON file with multiple JSON objects, each line contains valid JSON, but as a whole, it is not a valid JSON as there is no top-level ...
🌐
Homey Community
community.homey.app › flows
How do I save multiple json objects from an array to multiple tags - Flows - Homey Community Forum
April 17, 2022 - Built an advanced flow that connects to my cemm energymeter. Receive the response as a JSON array (as below for reference). I then save the ‘electric_power’ object as ‘Antwoord A’ tag for further use in flows. I am having diffucilties in creating more tags from the reponse below.
🌐
Javatpoint
javatpoint.com › json-array
JSON Array - javatpoint
JSON Array for beginners and professionals with examples of JSON with java, json array of string, json array of numbers, json array of booleans, json srray of objects, json multidimentional array. Learn JSON array example with object, array, schema, encode, decode, file, date etc.
🌐
Reddit
reddit.com › r/gamemaker › json_parse multiple arrays?
r/gamemaker on Reddit: json_parse multiple arrays?
June 3, 2022 -

Essentially what I've done is set up a JSON object containing two arrays:

var saveString = json_stringify(array1) + json_stringify(array2)

When I use the function json_parse to get them back, it only gives me the first array (array1). How can I call the second array from the json object?

🌐
Qlik Community
community.qlik.com › t5 › Design-and-Development › Multiple-Arrays-in-Json-Object › m-p › 2377484
Multiple Arrays in Json Object - Qlik Community - 2377484
January 6, 2022 - Attaching the sample Json file. We tried to put one sub job for each array and do lookup but it couldn't work it was giving like cross join. Please suggest on this. Thanks in advance. ... Ditto - same here! ... Hi, if you have a enterprise subscription , you can use structure and tHmap component to process multiple loop with one component.
🌐
Stack Overflow
stackoverflow.com › questions › 29218480 › how-to-create-json-array-of-multiple-json-object
php - how to create json array of multiple json object ? - Stack Overflow
<?php include_once "/db_connect.php"; $db = new DB_CONNECT(); $head='0'; if(empty($head)){ for($head=1;$head<20;$head++){ if(!empty($head)){ $flatp=mysql_query("SELECT co.id,co.user_id,co.cat_id,co.flatP,hds.HeadName,co.offer_name,u.shop_name,co.cost FROM createdoffers co INNER JOIN categories ct ON ct.id=co.cat_id INNER JOIN users u ON u.id=co.user_id INNER JOIN heads hds ON hds.id=ct.Head_id WHERE ct.Head_id='$head' AND ct.id=co.cat_id AND co.user_id=u.id ORDER BY co.flatP DESC LIMIT 1"); if (mysql_num_rows($flatp) >0) { $response["createdoffers"] = array(); while ($row = mysql_fetch_array($
Top answer
1 of 4
3

Give this a try:

$json = '
{
   "article_details":[  
      {  
         "article_code ":"000000000300028156 ",
         "diff_amnt ":"1 "
      },
      {  
         "article_code ":"000000000300028174 ",
         "diff_amnt ":"1 "
      },
      {  
         "article_code ":"000000000300028126 ",
         "diff_amnt ":"1 "
      }
   ],
   "article":[  
      {  
         "article_code ":"000000000300028156 ",
         "diff_amnt ":"1 "
      },
      {  
         "article_code ":"000000000300028174 ",
         "diff_amnt ":"1 "
      },
      {  
         "article_code ":"000000000300028126 ",
         "diff_amnt ":"1 "
      }
   ]
}';

$key = 'article_code '; // Since your key is 'article_code ' but not 'article_code', I have to do this
$dataObject = json_decode($json);
echo $dataObject->article_details[0]->$key; // This will out put: 000000000300028156 
$dataArray = json_decode($json, true);
echo $dataArray['article_details'][0]['article_code ']; // This will out put: 000000000300028156 
2 of 4
2

Use json_decode() to decode a JSON string, like this:

$json_array = json_decode($json, true);
                                  ^ When TRUE, returned objects will be converted into associative arrays.

So your code should be like this:

// Here $json is your json string
$json_array = json_decode($json, true);

foreach($json_array as $key => $arrays){
    echo $key . "<br />";
    foreach($arrays as $array){
        foreach($array as $key => $value){
            echo $key . " => " . $value . "<br />";
        }
    }
    echo "<br />";
}

Output:

article_details
article_code => 000000000300028156
diff_amnt => 1
article_code => 000000000300028174
diff_amnt => 1
article_code => 000000000300028126
diff_amnt => 1

article
article_code => 000000000300028156
diff_amnt => 1
article_code => 000000000300028174
diff_amnt => 1
article_code => 000000000300028126
diff_amnt => 1