PYnative

Python Programming

  • Learn Python
    • Python Tutorials
    • Python Basics
    • Python Interview Q&As
  • Exercises
    • Python Exercises
    • C Programming Exercises
    • C++ Exercises
  • Quizzes
  • Code Editor
    • Online Python Code Editor
    • Online C Compiler
    • Online C++ Compiler
Home » Python » JSON » Python Parse multiple JSON objects from file

Python Parse multiple JSON objects from file

Updated on: May 14, 2021 | 24 Comments

You are here because when you try to load and parse a JSON file with multiple JSON objects in Python, you received an error. json.decoder.JSONDecodeError: Extra data error. The reason is that the json.load() method can only handle a single JSON object.

Further Reading:

  • Solve Python JSON Exercise to practice Python JSON skills

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

{"id": 1, "name": "Ault", "class": 8, "email": "ault@pynative.com"}
{"id": 2, "name": "john", "class": 8, "email": "jhon@pynative.com"}
{"id": 3, "name": "josh", "class": 8, "email": "josh@pynative.com"}
{"id": 4, "name": "emma", "class": 8, "email": "emma@pynative.com"}

If your file contains a list of JSON objects, and you want to decode one object one-at-a-time, we can do it. To Load and parse a JSON file with multiple JSON objects we need to follow below steps:

  • Create an empty list called jsonList
  • Read the file line by line because each line contains valid JSON. i.e., read one JSON object at a time.
  • Convert each JSON object into Python dict using a json.loads()
  • Save this dictionary into a list called result jsonList.

Let’ see the example now.

import json

studentsList = []
print("Started Reading JSON file which contains multiple JSON document")
with open('students.txt') as f:
    for jsonObj in f:
        studentDict = json.loads(jsonObj)
        studentsList.append(studentDict)

print("Printing each JSON Decoded Object")
for student in studentsList:
    print(student["id"], student["name"], student["class"], student["email"])Code language: Python (python)

Output:

Started Reading JSON file which contains multiple JSON document
Printing each JSON Decoded Object
1 Ault 8 ault@pynative.com
2 john 8 jhon@pynative.com
3 josh 8 josh@pynative.com
4 emma 8 emma@pynative.com

So What Do You Think?

I want to hear from you. What do you think of this article? Or maybe I missed one of the ways to Parse multiple JSON objects from a file, Either way, let me know by leaving a comment below.

Also, try to solve the Python JSON Exercise to have a better understanding of Working with JSON Data in Python.

Filed Under: Python, Python JSON

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

TweetF  sharein  shareP  Pin

About Vishal

Image

I’m Vishal Hule, the Founder of PYnative.com. As a Python developer, I enjoy assisting students, developers, and learners. Follow me on Twitter.

Related Tutorial Topics:

Python Python JSON

All Coding Exercises:

C Exercises
C++ Exercises
Python Exercises

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 25+ questions
  • Each Quiz contains 25 MCQ
Exercises
Quizzes

Comments

  1. ImageChris says

    February 20, 2025 at 6:47 pm

    Thank you for your tutorial! My situation is exactly how you describe but with one addition: there is a single timestamp that tells the date the data was gathered. So in addition to those 4 data lines you have, there is one additional line in the file: { “timestamp”: “2024-12-10T13:45:00.000Z” }. I need to pass this data on and would prefer to send valid JSON.

    I have two questions:
    1. In your tutorial you state the file is not valid JSON, though each line is. If we wanted your example to be valid (I want to match a schema), how would the data change? An array or something?

    2. How is something like this timestamp added to a schema that has this list of tuples?

    Thanks again!

    Reply
    • ImageChris says

      February 21, 2025 at 12:00 am

      I have a schema and test data to match. If anyone gets here and would like to see them, hit reply and I should be notified so I can get it to you!

      Reply
  2. ImageTarun says

    October 12, 2022 at 5:12 pm

    Hey, please help. This is my data, and it is an invalid Json, is there any way to get all the values of the data

    {
    	"data": {
    		"blah": "blah",
    		"blah": "blah",
    		"blah": "blah"
    	},
    	"metadata": {
    		"blah": "blah",
    		"blah": "blah",
    		"blah": "blah"
    	}
    }{
    	"data": {
    		"blah": "blah",
    		"blah": "blah",
    		"blah": "blah"
    	},
    	"metadata": {
    		"blah": "blah",
    		"blah": "blah",
    		"blah": "blah"
    	}
    }
    Reply
    • ImageDavid Dreggors says

      March 22, 2023 at 1:33 am

      I would love to see the code to parse this as well, several commands write json out like this for multiple objects.

      Reply
  3. ImagePooja says

    March 29, 2022 at 12:02 pm

    How would you read the json file of it was supported by brackets and then divide it into smaller json file .

    Reply
  4. ImageRajesh says

    November 9, 2021 at 2:12 pm

    How would you achieve this if we have multiple json separated by space not by line.

    Reply
    • ImageRainer Chan says

      January 2, 2022 at 7:20 pm

      
      import json
      
      studentsList = []
      print("Started Reading JSON file which contains multiple JSON document")
      with open('students.txt') as f:
          braceCount = 0
          jsonStr = ''
          for jsonObj in f:
              braceCount += jsonObj.count('{')
              braceCount -= jsonObj.count('}')
              jsonStr += jsonObj
              if (braceCount == 0):
                  studentDict = json.loads(jsonStr)
                  studentsList.append(studentDict)
                  jsonStr = ''
      
      print("Printing each JSON Decoded Object")
      for student in studentsList:
          print(student["id"], student["name"], student["class"], student["email"])
      Reply
      • ImageSuruthi says

        September 20, 2023 at 3:21 pm

        Thanks a lot, it saved my time..

        Reply
  5. ImageAnggara Mahardika says

    October 6, 2021 at 2:52 pm

    Hi.. It worked for Me. Thanks for sharing

    Reply
  6. ImagePriyam says

    August 4, 2021 at 12:01 am

    Hey how would I process if my json is in below format:

    [{"id": 1, "name": "Ault", "class": 8, "email": "ault@pynative.com"}
    {"id": 2, "name": "john", "class": 8, "email": "jhon@pynative.com"}]
    [{"id": 3, "name": "josh", "class": 8, "email": "josh@pynative.com"}
    {"id": 4, "name": "emma", "class": 8, "email": "emma@pynative.com"}]

    It is like multiple lists and inside there are multiple dictionaries

    Reply
    • ImageAshis says

      October 22, 2021 at 1:01 am

      This is in JSON format . kindly convert it to object dictionary with loads

      Reply
  7. Imagearchana says

    May 14, 2021 at 1:07 pm

    hi this code worked for me and it helped
    thank you

    Reply
  8. Imageroshan says

    December 31, 2020 at 3:59 pm

    I want to know how you can convert multiple jason file to single jason file and insert in dynamo db.
    Jason files picked from s3 bucket.

    Reply
  9. ImageCharie says

    November 16, 2020 at 3:11 am

    if our data is in below format:

    { "id": 1, "name": "Ault", "class": 8, "email": "ault@pynative.com" }
    { "id": 2, "name": "john", "class": 8, "email": "jhon@pynative.com" }

    it throws errors. Can anyone put light on this why is it so?

    Reply
  10. ImageGermain Mallard says

    August 6, 2020 at 4:40 am

    Useful method – thanks for your post

    Reply
  11. ImageNaveen says

    July 30, 2020 at 1:10 pm

    i have a doubt in my code regarding getting multiple inputs from the user and while storing i got an error

    Reply
  12. ImageZ says

    July 21, 2020 at 9:31 pm

    hello, thanks for your tutorial. After applying the code, i got the following error:
    JSONDecodeError: Extra data: line 1 column 806 (char 805)

    What do you advise?

    Thanks and best regards,

    Reply
    • ImageVishal says

      July 22, 2020 at 8:51 pm

      hey, Can you please provide me your code.

      Reply
  13. ImageManthan Admane says

    June 17, 2020 at 11:50 pm

    Great post! Helped a lot. Thank you : )

    Reply
    • ImageVishal says

      June 20, 2020 at 7:11 pm

      I’m glad it helped you, Manthan Admane.

      Reply
  14. ImageKewal Singh says

    June 13, 2020 at 10:13 pm

    Reading a .json file to create a data frame is difficult. There might be syntax or version issues but whatever solutions different experts have suggested, none of them works. Shall appreciate highly if you give an example of reading a multiobject .json file for creating a dataframe.

    Reply
  15. ImageFocus says

    May 9, 2020 at 4:33 am

    Thanks for this explanation, I am currently facing similar problem, but it’s more difficult because the file has over 1 million lines of json object. How do I do these without using memory?

    Reply
    • ImageDiegosGreyHat says

      March 22, 2022 at 3:15 am

      You have multiple objects on ONE file? OR one OBJECT that needs a million lines to store? Big difference…

      If it’s the former, you can piecemeal it and likely only load the objects you need (1 at a time)… Or better yet, put them in to separate files in a special folder. Look through items in that folder. Boom no memory issues.

      If it’s the latter, then yeah you are right. Loading that much into memory, not the best idea. You need to see if you really need 1 million lines of data for ONE OBJECT.. You can always write your own serialize() and deserialize() functions, so you only write the data you need to a file.

      Reply
      • ImageJPR says

        April 22, 2022 at 7:51 pm

        Hi, I have a single JSON file with multiple objects, but each object is split over multiple lines (so it is not like in the example above, where one object is in one line). It looks like this:

         [
            {
                "Subject": "1",
                "Body": {
                    "ContentType": "HTML",
                    "Content": "1"
                },
                "Start": {
                    "DateTime": "2014-02-02T18:00:00",
                    "TimeZone": "Europe/Paris"
                },
                "End": {
                    "DateTime": "2014-02-02T19:00:00",
                    "TimeZone": "Europe/Paris"
                }
            },
            // some other objects ...
            {
                "Subject": "n",
                "Body": {
                    "ContentType": "HTML",
                    "Content": "n"
                },
                "Start": {
                    "DateTime": "2014-02-02T18:00:00",
                    "TimeZone": "Europe/Paris"
                },
                "End": {
                    "DateTime": "2014-02-02T19:00:00",
                    "TimeZone": "Europe/Paris"
                }
            }
        ] 

        Any advice on how to load this into Python, or at least on how to split this file into individual-object files?

        Reply

Leave a Reply Cancel reply

your email address will NOT be published. all comments are moderated according to our comment policy.

Use <pre> tag for posting code. E.g. <pre> Your entire code </pre>

In: Python Python JSON
TweetF  sharein  shareP  Pin

  Python JSON

  • Python JSON Guide
  • JSON Serialization
  • JSON Parsing
  • JSON Validation
  • PrettyPrint JSON
  • Make Python Class JSON serializable
  • Convert JSON Into Custom Python Object
  • Python JSON Unicode
  • Parse JSON using Python requests
  • Post JSON using Python requests
  • Serialize DateTime into JSON
  • Serialize Python Set into JSON
  • Serialize NumPy array into JSON
  • Parse multiple JSON objects from file
  • Parse Nested JSON
  • Python JSON Exercise

 Explore Python

  • Python Tutorials
  • Python Exercises
  • Python Quizzes
  • Python Interview Q&A
  • Python Programs

All Python Topics

Python Basics Python Exercises Python Quizzes Python Interview Python File Handling Python OOP Python Date and Time Python Random Python Regex Python Pandas Python Databases Python MySQL Python PostgreSQL Python SQLite Python JSON

About PYnative

PYnative.com is for Python lovers. Here, You can get Tutorials, Exercises, and Quizzes to practice and improve your Python skills.

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

  • Twitter
  • Facebook
  • Sitemap

Explore Python

  • Learn Python
  • Python Basics
  • Python Databases
  • Python Exercises
  • Python Quizzes
  • Online Python Code Editor
  • Python Tricks

Coding Exercises

  • C Exercises
  • C++ Exercises
  • Python Exercises

Legal Stuff

  • About Us
  • Contact Us

We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our:

  • Terms Of Use
  • Privacy Policy
  • Cookie Policy

Copyright © 2018–2026 pynative.com

Advertisement