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.

🌐
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.
🌐
Polygon
docshield.tungstenautomation.com › KTA › en_us › 7.9.0-ud9cfx6hos › help › designer › All_Shared › SystemData › c_dmjsonexamples.html
Examples of data models using JSON sample
The above JSON sample creates the following 'Employee' model.. In addition to the simple employee details, this sample includes 'contactdetails' as nested object, which includes Phone and Email fields.
🌐
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?

Top answer
1 of 7
2

Lean towards option 1, as it's a more expected format.

Option 1 works with JSON as it's designed to be used and therefore benefits from what JSON offers (a degree of human readability, which is good for debugging, and straightforward parsing, which is good for limiting entire categories of bugs to begin with).

Option 2 begrudgingly adopts JSON and subverts many of the benefits. If you don't want human readability, use protobuf or something similar... AIWalker's "CSV"-like approach isn't terrible either. It is marginally better (readable) than splitting objects apart and recombining them. But, this is still not as good (readable) as using JSON "as designed".

Also bear in mind, your API responses are also likely going to be gzipped. Most of the repetition in option 1 will be quickly and transparently condensed over the wire.

As an aside, if you're moving a lot of data, also consider JSONL or paginated results. Pagination can be especially helpful for web clients, as it places natural pauses in the processing, providing a degree of "organic" protection against UI lockups.

2 of 7
3

A list of objects is easier to work with. You can use append, map, filter... All the nice things JS Arrays have which manual indexing doesn't. And there's no way to get out of sync, so that's an entire class of bugs gone.

If you're worried about efficiency:

  • Measure (premature optimization is the root of all evil)
  • Consider the list of lists trick AIWalker proposed
  • Consider an outright binary format
  • Make sure gzip is enabled
  • Measure (it's worth saying twice)
🌐
Microsoft Learn
learn.microsoft.com › en-ie › answers › questions › 1857170 › deserializing-multiple-object-lists-from-a-json-fi
Deserializing multiple Object Lists from a Json file - Microsoft Q&A
Public Class Data Public Property FIDs As List(Of FID) Public Property Profiles As List(Of Profile) End Class Function LoadData(filename As String) As Data Dim json = System.IO.File.ReadAllText(filename) Dim data = JsonConvert.DeserializeObject(Of Data)(json) Return data End Function · Now you have access to both sets of objects and can process them however you want. With the above code I'm able to read in your entire JSON file with all the content set properly.
Find elsewhere
🌐
CodeProject
codeproject.com › Questions › 1164374 › How-to-add-multiple-object-in-JSON-object-array
How to add multiple object in JSON object/array?
Do not try and find the page. That’s impossible. Instead only try to realise the truth - For those who code; Updated: 1 Jul 2007
🌐
UiPath Community
forum.uipath.com › help › studio
JSON Array with multiple json objects and json arrays - Studio - UiPath Community Forum
September 25, 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, ...
🌐
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 list or object definition. We can call JSON a valid ...
🌐
Python Forum
python-forum.io › thread-27109.html
Parse JSON multiple objects
I'm having trouble parsing multiple objects within a JSON array. I can get my code to work, but I have to manipulate the JSON file which I shouldn't have to do. I'm on Python 3, and here's my code: import json tradingList = [] print with open('par...
🌐
TutorialsPoint
tutorialspoint.com › how-can-i-filter-json-data-with-multiple-objects
How can I filter JSON data with multiple objects?
To filter JSON data with multiple objects, you can use the concept of filter along with ==. Example const jsonObject= [ { studentId:101, student
Top answer
1 of 3
6

I think the problem is that you are overwriting the file with fs.writeFileSync().

You should use fs.appendFileSync() to add new data to the end of the file. See the node docs.

https://nodejs.org/api/fs.html#fs_fs_appendfilesync_file_data_options

2 of 3
2

if you are writing all data at once, then you need to do create an array, push all objects to array and write the array to file

function insertDatasJson (res) {
    let fs = require('fs');
    let base = require('../public/json/template.json');
    let result = [];
    for (/*you loop statmeent*/) {
      let obj = JSON.parse(JSON.stringify(base));  // or your preferred way of deep copying
      obj.Subject = 'f';
      obj.Body.Content = 'e';
      obj.Start.DateTime = '2016-11-13T08:30:00';
      obj.End.DateTime = '2016-11-13T17:30:00';
      result.push(obj);
    }

    fs.writeFileSync('./public/json/output/jsonOutput.json', JSON.stringify(result, null, 4));
}

Or if you want to write data in multiple runs, then

function insertDatasJson (res) {
    let fs = require('fs');
    let base = require('../public/json/template.json');
    let data = require('./public/json/output/jsonOutput.json');
    base.Subject = 'f';
    base.Body.Content = 'e';
    base.Start.DateTime = '2016-11-13T08:30:00';
    base.End.DateTime = '2016-11-13T17:30:00';
    data.push(base);
    fs.writeFileSync('./public/json/output/jsonOutput.json', JSON.stringify(data, null, 4));
}

However, in second case, you need to add some code to handle the case of first run when there is no existing data in the output file, or file doesn't exist. Another way to handle that condition would be to initialize the output file with empty JSON array

[]

EDIT: In both cases, appending to the existing file will not work as it will generate invalid JSON.

🌐
SmartBear Community
community.smartbear.com › smartbear community › readyapi › readyapi questions
How to test a JSON response with multiple objects with the same name | SmartBear Community
we will have multiple objects called test1), we've been having difficulties finding a way to create assertions to allow us to check that the each object contains the correct value without manually creating properties for each object. Ideally, we want to be able to use an Excel spreadsheet which will show each JSON section on a separate row (e.g.
🌐
Microsoft Power Platform Community
powerusers.microsoft.com › t5 › Building-Flows › Choose-one-JSON-object-from-multiple-based-on-specific-value › td-p › 1442635
Choose one JSON object from multiple based on specific value
Like any other community in tech, companies in the Dynamics community are missing out on talent, innovation, top line and bottom-line growth, employee retention and market share. Why? Because of lack of diversity within the company - from executive leadership to contributor levels.
🌐
PYnative
pynative.com › home › python › json › python parse multiple json objects from file
Python Parse multiple JSON objects from file | Solve ValueError: Extra data
May 14, 2021 - When you try to load and parse ... only when there is a top-level list or object definition. For example, you wanted to read the following JSON file, filter some data, and store it into a new JSON file....
🌐
GitHub
github.com › danielaparker › jsoncons › blob › master › examples › input › multiple-json-objects.json
jsoncons/examples/input/multiple-json-objects.json at master · danielaparker/jsoncons
A C++, header-only library for constructing JSON and JSON-like data formats, with JSON Pointer, JSON Patch, JSON Schema, JSONPath, JMESPath, CSV, MessagePack, CBOR, BSON, UBJSON - jsoncons/examples/input/multiple-json-objects.json at master · danielaparker/jsoncons
Author   danielaparker
🌐
GeeksforGeeks
geeksforgeeks.org › python › extract-multiple-json-objects-from-one-file-using-python
Extract Multiple JSON Objects from one File using Python - GeeksforGeeks
July 23, 2025 - Below are some approaches of extracting multiple JSON Objects from one file in Python: ... This approach involves reading file content line by line and parsing each line individually as JSON. json.load() is a built in function present in json module that takes a file object or a string which contains JSON data as input and returns a Python object.