Menu Close

How to load and parse a JSON file with multiple JSON objects with Python?

Sometimes, we want to load and parse a JSON file with multiple JSON objects with Python.

In this article, we’ll look at how to load and parse a JSON file with multiple JSON objects with Python.

How to load and parse a JSON file with multiple JSON objects with Python?

To load and parse a JSON file with multiple JSON objects with Python, we can use open the file and parse the JSON object in each line.

For instance, we write

import json

data = []
with open('file') as f:
    for line in f:
        data.append(json.loads(line))

to open the file file with open.

And then we loop through each line in f with a for loop.

In the loop, we call data.append with the JSON loaded with json.loads(line) to append the dict with the parsed JSON into the data list.

Conclusion

To load and parse a JSON file with multiple JSON objects with Python, we can use open the file and parse the JSON object in each line.

Posted in Python, Python Answers