There are several problems with the logic of your code.

ss = s.read()

reads the entire file s into a single string. The next line

for line in ss:

iterates over each character in that string, one by one. So on each loop line is a single character. In

    line = ss[7:]

you are getting the entire file contents apart from the first 7 characters (in positions 0 through 6, inclusive) and replacing the previous content of line with that. And then

T.append(json.loads(line))

attempts to convert that to JSON and store the resulting object into the T list.


Here's some code that does what you want. We don't need to read the entire file into a string with .read, or into a list of lines with .readlines, we can simply put the file handle into a for loop and that will iterate over the file line by line.

We use a with statement to open the file, so that it will get closed automatically when we exit the with block, or if there's an IO error.

import json

table = []
with open('simple.json', 'r') as f:
    for line in f:
        table.append(json.loads(line[7:]))

for row in table:
    print(row)

output

{'color': '33ef', 'age': '55', 'gender': 'm'}
{'color': '3444', 'age': '56', 'gender': 'f'}
{'color': '3999', 'age': '70', 'gender': 'm'}

We can make this more compact by building the table list in a list comprehension:

import json

with open('simple.json', 'r') as f:
    table = [json.loads(line[7:]) for line in f]

for row in table:
    print(row)
Answer from PM 2Ring on Stack Overflow
Top answer
1 of 4
9

There are several problems with the logic of your code.

ss = s.read()

reads the entire file s into a single string. The next line

for line in ss:

iterates over each character in that string, one by one. So on each loop line is a single character. In

    line = ss[7:]

you are getting the entire file contents apart from the first 7 characters (in positions 0 through 6, inclusive) and replacing the previous content of line with that. And then

T.append(json.loads(line))

attempts to convert that to JSON and store the resulting object into the T list.


Here's some code that does what you want. We don't need to read the entire file into a string with .read, or into a list of lines with .readlines, we can simply put the file handle into a for loop and that will iterate over the file line by line.

We use a with statement to open the file, so that it will get closed automatically when we exit the with block, or if there's an IO error.

import json

table = []
with open('simple.json', 'r') as f:
    for line in f:
        table.append(json.loads(line[7:]))

for row in table:
    print(row)

output

{'color': '33ef', 'age': '55', 'gender': 'm'}
{'color': '3444', 'age': '56', 'gender': 'f'}
{'color': '3999', 'age': '70', 'gender': 'm'}

We can make this more compact by building the table list in a list comprehension:

import json

with open('simple.json', 'r') as f:
    table = [json.loads(line[7:]) for line in f]

for row in table:
    print(row)
2 of 4
8

If you use Pandas you can simply write df = pd.read_json(f, lines=True)

as per doc the lines=True:

Read the file as a json object per line.

🌐
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 - Entire file content will be read and by using re.findall() method the defined pattern will be applied to the file content and it will return the list of strings of json objects found in a file, each string is passed to the json.loads() method ...
Discussions

How do I use Python to read multiple JSON files and export specific values to a CSV?
I am not a programmer and have no experience with Pyton, so I would really appreciate any help to solve the few remaining issues I’ll explain bellow: What I am trying to do is collect a few but same values from many .json files and get them into a spreadsheet to work with later. More on discuss.python.org
🌐 discuss.python.org
0
September 7, 2022
python - How to extract multiple JSON objects from one file? - Stack Overflow
Below I have prototyped a reader function which reads each json object individually and returns a generator. The basic idea is to signal the reader to split on the carriage character "\n" (or "\r\n" for Windows). Python can do this with the file.readline() function. More on stackoverflow.com
🌐 stackoverflow.com
how to load multiple json objects in python - Stack Overflow
Traceback (most recent call last): ... object_pairs_hook=object_pairs_hook, **kw) File "/usr/lib/python3.5/json/__init__.py", line 319, in loads return _default_decoder.decode(s) File "/usr/lib/python3.5/json/decoder.py", line 342, in decode raise JSONDecodeError("Extra data", s, end) json.decoder.JSONDecodeError: Extra data: line 7 column 1 (char 46) >>> I've read the related ... More on stackoverflow.com
🌐 stackoverflow.com
September 26, 2018
Help with decoding JSON file with multiple Objects
Load the content in the top level array and append to that, then write that new list to the file in write mode. That should work. More on reddit.com
🌐 r/learnpython
4
1
July 10, 2017
🌐
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?

🌐
Python Forum
python-forum.io β€Ί thread-27109.html
Parse JSON multiple objects
May 26, 2020 - 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...
🌐
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()
🌐
Python.org
discuss.python.org β€Ί python help
How do I use Python to read multiple JSON files and export specific values to a CSV? - Python Help - Discussions on Python.org
September 7, 2022 - I am not a programmer and have no experience with Pyton, so I would really appreciate any help to solve the few remaining issues I’ll explain bellow: What I am trying to do is collect a few but same values from many .js…
🌐
Medium
medium.com β€Ί @datajournal β€Ί how-to-parse-json-data-with-python-99069a405e2b
How to Parse JSON Data With Python (EASY) | Medium
May 29, 2024 - The β€œask for forgiveness” approach is more common in Python, assuming that errors are a regular part of program flow. It provides a graceful way of handling errors, making the code easier to read and write. After modifying JSON data, you may want to save it back to a JSON file or export it as a JSON string. The `json.dump()` method saves a JSON object to a file, while `json.dumps()` returns a JSON string representation of an object.
Find elsewhere
🌐
Real Python
realpython.com β€Ί python-json
Working With JSON Data in Python – Real Python
August 20, 2025 - Learn how to work with JSON data in Python using the json module. Convert, read, write, and validate JSON files and handle JSON data for APIs and storage.
🌐
Python
docs.python.org β€Ί 3 β€Ί library β€Ί json.html
json β€” JSON encoder and decoder
2 weeks ago - fp (file-like object) – A .read()-supporting text file or binary file containing the JSON document to be deserialized. cls (a JSONDecoder subclass) – If set, a custom JSON decoder. Additional keyword arguments to load() will be passed to the constructor of cls. If None (the default), JSONDecoder is used. object_hook (callable | None) – If set, a function that is called with the result of any JSON object literal decoded (a dict).
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"]
🌐
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 - The . option tells jq to output the entire JSON object. The file1.json, file2.json, and file3.json options tell jq to read the JSON files from those files. The > combined.json option tells jq to write the combined JSON file to the combined.json file. I hope this helps! ... As a developer with a passion for problem-solving, I'm always seeking new challenges to push my skills to the limit
🌐
GeeksforGeeks
geeksforgeeks.org β€Ί how-to-merge-multiple-json-files-using-python
How to Merge Multiple JSON Files Using Python - GeeksforGeeks
April 28, 2025 - In this article, we will discuss multiple ways to parse nested JSON in Python using built-in modules and libraries like json, recursion techniques and even pandas.What is Nested JSONNested JSON refers to a JSON object that cont ... Converting CSV to JSON using Python involves reading the CSV file, converting each row into a dictionary and then saving the data as a JSON file.
🌐
YouTube
youtube.com β€Ί codedash
python read json file with multiple objects - YouTube
Download this code from https://codegive.com Sure, I can help you with that! Here's a tutorial on reading a JSON file with multiple objects in Python, along ...
Published Β  February 2, 2024
Views Β  5
🌐
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 ...
🌐
Medium
medium.com β€Ί @programinbasic β€Ί merge-multiple-json-files-into-one-in-python-65c009aad81d
Merge Multiple JSON files into One in Python | by ProgrammingBasic | Medium
January 17, 2024 - It imports the pandas library for working with DataFrames. It defines a function called merge_json_files() that takes a list of JSON file paths as a parameter. Inside the function, it initializes an empty DataFrame called merged_data to hold the merged data. It starts a loop over each file path passed to the function. Inside the loop, it opens each JSON file and uses pd.read_json() to load the data into a DataFrame called data.
🌐
GeeksforGeeks
geeksforgeeks.org β€Ί read-json-file-using-python
Read JSON file using Python - GeeksforGeeks
The full form of JSON is JavaScript Object Notation. It means that a script (executable) file which is made of text in a programming language, is used to store and transfer the data. Python supports JSON through a built-in package called JSON. To use this feature, we import the JSON package in Python script. The text in JSON is done through quoted-string which contains the value in key-value mapping within { }. ... import json # Open and read the JSON file with open('data.json', 'r') as file: data = json.load(file) # Print the data print(data)
Published Β  April 2, 2025