Update: I wrote a solution that does not require reading the entire file in one go. It is too big for a stackoverflow answer, but can be found here jsonstream.

You can use json.JSONDecoder.raw_decode to decode arbitarily big strings of "stacked" JSON (so long as they can fit in memory). raw_decode stops once it has a valid object and returns the last position where was not part of the parsed object. It is poorly documented [1] (see footer), but you can pass this position back to raw_decode and it start parsing again from that position. Unfortunately, the Python json module doesn ot accept strings that have prefixing whitespace. So we need to search to find the first non-whitespace part of your document.

from json import JSONDecoder, JSONDecodeError
import re

NOT_WHITESPACE = re.compile(r'\S')

def decode_stacked(document, idx=0, decoder=JSONDecoder()):
    while True:
        match = NOT_WHITESPACE.search(document, idx)
        if not match:
            return
        idx = match.start()
        
        try:
            obj, idx = decoder.raw_decode(document, idx)
        except JSONDecodeError:
            # do something sensible if there's some error
            raise
        yield obj

s = """

{"a": 1}  


   [
1
,   
2
]


"""

for obj in decode_stacked(s):
    print(obj)

prints:

{'a': 1}
[1, 2]

Note About Missing Documentation

The current signature of raw_decode() dates from 2009, when simplejson was ported into the standard library. The documentation for raw_decode() in simplejson mentions an optional idx argument that can be used to start parsing at an offset. Given that the signature of raw_decode() has not changed since 2009, I think it is fair to assume the API is fairly stable. Especially as decode() uses the idx argument of raw_decode() to ignore prefixing whitespace when parsing a string. And this is exactly what this answer is using the idx argument for too. The documentation of raw_decode() in simplejson is:

raw_decode(s[, idx=0])

Decode a JSON document from s (a str or unicode beginning with a JSON document) starting from the index idx and return a 2-tuple of the Python representation and the index in s where the document ended.

This can be used to decode a JSON document from a string that may have extraneous data at the end, or to decode a string that has a series of JSON objects.

JSONDecodeError will be raised if the given JSON document is not valid.

Answer from Dunes on Stack Overflow
Top answer
1 of 6
99

Update: I wrote a solution that does not require reading the entire file in one go. It is too big for a stackoverflow answer, but can be found here jsonstream.

You can use json.JSONDecoder.raw_decode to decode arbitarily big strings of "stacked" JSON (so long as they can fit in memory). raw_decode stops once it has a valid object and returns the last position where was not part of the parsed object. It is poorly documented [1] (see footer), but you can pass this position back to raw_decode and it start parsing again from that position. Unfortunately, the Python json module doesn ot accept strings that have prefixing whitespace. So we need to search to find the first non-whitespace part of your document.

from json import JSONDecoder, JSONDecodeError
import re

NOT_WHITESPACE = re.compile(r'\S')

def decode_stacked(document, idx=0, decoder=JSONDecoder()):
    while True:
        match = NOT_WHITESPACE.search(document, idx)
        if not match:
            return
        idx = match.start()
        
        try:
            obj, idx = decoder.raw_decode(document, idx)
        except JSONDecodeError:
            # do something sensible if there's some error
            raise
        yield obj

s = """

{"a": 1}  


   [
1
,   
2
]


"""

for obj in decode_stacked(s):
    print(obj)

prints:

{'a': 1}
[1, 2]

Note About Missing Documentation

The current signature of raw_decode() dates from 2009, when simplejson was ported into the standard library. The documentation for raw_decode() in simplejson mentions an optional idx argument that can be used to start parsing at an offset. Given that the signature of raw_decode() has not changed since 2009, I think it is fair to assume the API is fairly stable. Especially as decode() uses the idx argument of raw_decode() to ignore prefixing whitespace when parsing a string. And this is exactly what this answer is using the idx argument for too. The documentation of raw_decode() in simplejson is:

raw_decode(s[, idx=0])

Decode a JSON document from s (a str or unicode beginning with a JSON document) starting from the index idx and return a 2-tuple of the Python representation and the index in s where the document ended.

This can be used to decode a JSON document from a string that may have extraneous data at the end, or to decode a string that has a series of JSON objects.

JSONDecodeError will be raised if the given JSON document is not valid.

2 of 6
38

Use a json array, in the format:

[
{"ID":"12345","Timestamp":"20140101", "Usefulness":"Yes",
  "Code":[{"event1":"A","result":"1"},…]},
{"ID":"1A35B","Timestamp":"20140102", "Usefulness":"No",
  "Code":[{"event1":"B","result":"1"},…]},
{"ID":"AA356","Timestamp":"20140103", "Usefulness":"No",
  "Code":[{"event1":"B","result":"0"},…]},
...
]

Then import it into your python code

import json

with open('file.json') as json_file:

    data = json.load(json_file)

Now the content of data is an array with dictionaries representing each of the elements.

You can access it easily, i.e:

data[0]["ID"]
Discussions

Multiple objects in JSON file
You’re not getting valid JSON if there’s more than one top level object. More on reddit.com
🌐 r/learnpython
7
3
February 5, 2020
Collecting multiple .json objects in one .json file?
Collecting multiple .json objects in one .json... Learn more about coco, json, multiple json files in a single json file More on mathworks.com
🌐 mathworks.com
1
0
November 1, 2021
Combine multiple json files into one json file
Describe the issue/error/question I would like to read multiple json file from the local disk and then combine all the json data from all the files into one main json data file. What is the error message (if any)? I am not getting any error but I have been trying to use read binary files and ... More on community.n8n.io
🌐 community.n8n.io
0
0
June 15, 2022
Reading multiple json objects from a single file
Thanks for the PowerShell idea u/slashd , I was able to do it using this code: $outputFilePath = "C:\Users\Downloads\pipeline\JSONJOINTEST.txt" $sourceFolderPath = "C:\Users\Downloads\pipeline\pipeline" $jsonFiles = Get-ChildItem -Path $sourceFolderPath -Filter "*.json" $mergedObjects = @() foreach ($jsonFile in $jsonFiles) { try { $jsonContent = Get-Content -Path $jsonFile.FullName -Raw $jsonObject = ConvertFrom-Json -InputObject $jsonContent $mergedObjects += $jsonObject } catch [System.ArgumentException] { Write-Warning "Skipping file $($jsonFile.Name) due to invalid JSON content." } } $mergedJson = $mergedObjects | ConvertTo-Txt $mergedJson | Set-Content -Path $outputFilePath More on reddit.com
🌐 r/SQLServer
6
2
January 10, 2023
People also ask

How do I merge multiple JSON files?
Upload your JSON files using the file picker or drag and drop. You can add as many files as needed. Click "Merge" to combine them into a single file, then download the result.
🌐
agentsfordata.com
agentsfordata.com › json tools › json merge
Merge JSON Files Online Free - Combine Multiple JSONs
Is there a limit on how many JSON files I can merge?
No, there's no limit on the number of files. You can merge hundreds of JSON files at once. All processing happens in the cloud with no file size restrictions.
🌐
agentsfordata.com
agentsfordata.com › json tools › json merge
Merge JSON Files Online Free - Combine Multiple JSONs
Do I need to create an account to merge JSON files?
No account required for basic merging. Simply upload your files and download the merged result. Creating a free account unlocks additional features.
🌐
agentsfordata.com
agentsfordata.com › json tools › json merge
Merge JSON Files Online Free - Combine Multiple JSONs
🌐
Medium
ekapramudita.medium.com › combining-multiple-json-files-into-a-single-json-file-8d6e608483e0
Combining Multiple JSON Files Into A Single JSON File | by Eka Aditya Pramudita | Medium
June 7, 2021 - In this article, I will show you an example of JSON data processing. The goal is to make JSON files containing one observation per file in a folder combined into a single JSON file.
🌐
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?

🌐
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 - 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 ...
🌐
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 - To parse a JSON file with multiple JSON objects read one JSON object at a time and Convert it into Python dict using a json.loads()
Find elsewhere
🌐
MathWorks
mathworks.com › matlabcentral › answers › 1576358-collecting-multiple-json-objects-in-one-json-file
Collecting multiple .json objects in one .json file? - MATLAB Answers - MATLAB Central
November 1, 2021 - You can open the json files and append them one after another. Following is how you can achieve it. ... Here 'combined.json' will be your desired json file. To perform the above operation on Linux system without MATLAB, you may run the following commands in terminal
🌐
DEV Community
dev.to › vinodgarg › multiple-json-objects-in-a-single-file-kdb
Multiple Json objects in a single file - DEV Community
May 7, 2019 - we have multiple json objects stored in array format in a file (30K records per file). I am looking for java code which can be used to split json objects into multiple objects and provide the json object in variable. Also, Is there any way which can be used to read array element one by one instead ...
🌐
Medium
medium.com › @abdelfatahmennoun4 › how-to-combine-multiple-json-files-into-a-single-json-file-c2ed3dc372c2
How to Combine Multiple JSON Files into a Single JSON File | by Abdelfatah MENNOUN | Medium
May 19, 2023 - Use the jq command to combine all the JSON files into a single JSON file. Here is an example of how to combine multiple JSON files into a single JSON file using the jq command-line tool:
🌐
Microsoft Fabric Community
community.fabric.microsoft.com › t5 › Service › How-to-merge-multiple-JSON-files-into-one › td-p › 4005497
How to merge multiple JSON files into one - Microsoft Fabric Community
June 28, 2024 - import json # Create a list of all the JSON files that you want to combine. json_files = ["file1.json", "file2.json", "file3.json"] # Create an empty list to store the Python objects. python_objects = [] # Load each JSON file into a Python object. for json_file in json_files: with open(json_file, "r") as f: python_objects.append(json.load(f)) # Dump all the Python objects into a single JSON file. with open("combined.json", "w") as f: json.dump(python_objects, f, indent=4) ... How to Combine Multiple JSON Files into a Single JSON File | by Abdelfatah MENNOUN | Medium python 3.x - Merge multiple JSON files (more than two) - Stack Overflow
🌐
GeeksforGeeks
geeksforgeeks.org › python › how-to-merge-multiple-json-files-using-python
How to Merge Multiple JSON Files Using Python - GeeksforGeeks
July 23, 2025 - In this example, the merge_json_files function reads JSON data from multiple files specified by file_paths using a list comprehension. The data is then stored in a list named merged_data.
🌐
n8n
community.n8n.io › questions
Combine multiple json files into one json file - Questions - n8n Community
June 15, 2022 - Describe the issue/error/question I would like to read multiple json file from the local disk and then combine all the json data from all the files into one main json data file. What is the error message (if any)? I am not getting any error but I have been trying to use read binary files and ...
🌐
Reddit
reddit.com › r/sqlserver › reading multiple json objects from a single file
r/SQLServer on Reddit: Reading multiple json objects from a single file
January 10, 2023 -

Hey all, I’ve got an annoying situation. We have a system, that we don’t control, that outputs JSON to a single file where each row of the file is a json object. All of these objects are not wrapped in a larger JSON array. That piece is important. Each row has all the same keys, just different values per key.

We need to import all of these objects into SQL server mapping the keys to columns. We got it working for the most part by following: https://www.sqlshack.com/import-json-data-into-sql-server/

Declare @JSON varchar(max) SELECT @JSON=BulkColumn FROM OPENROWSET (BULK 'C:\sqlshack\Results.JSON', SINGLE_CLOB) import SELECT * FROM OPENJSON (@JSON) WITH ( [FirstName] varchar(20), [MiddleName] varchar(20), [LastName] varchar(20), [JobTitle] varchar(20), [PhoneNumber] nvarchar(20), [PhoneNumberType] varchar(10), [EmailAddress] nvarchar(100), [EmailPromotion] bit

)

That works but it only reads the first object it finds. Is there anyway to tell SQL Server “loop over all the lines of this file and import them off?”

Ideally the other system would wrap all the lines in a valid JSON array but they don’t and we can’t make them.

Warning: im a SQL server noob, so this may be very simple but I can’t find anything about this online

Edit: I haven’t tried it yet but this might be the answer just in case someone else comes across this post in the far off future.

https://learn.microsoft.com/en-us/archive/blogs/sqlserverstorageengine/loading-line-delimited-json-files-in-sql-server-2016

Basically you have to hand a SQL server format file.

🌐
Quora
quora.com › How-can-I-load-more-JSON-files-into-one-JSON-file-and-then-read-it-in-console-JavaScript
How to load more JSON files into one JSON file, and then read it in console (JavaScript) - Quora
Yes u can use mulitple JSON into one and read it in console by using concept of Array .. Array helps in getting ur data in right format . u can also do the same by means of concatantion but it might give u serveral errors like JSON parsing errors .
🌐
Itversity
kaizen.itversity.com › multiple-json-documents-in-files
Multiple JSON Documents in Files – Kaizen
If you use pandas, it is straight forward. However, we will talk about using pandas later. We cannot use json module directly. Here are the steps to use JSON module. Create file type object by passing the path to open. Use read to read the content in the file into ...
🌐
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 ...