How to Read and Parse JSON Data in Python?

Reading time: 5 min read
Muninder Adavelli
Written by
Muninder Adavelli

Updated · Dec 08, 2023

Muninder Adavelli
Digital Growth Strategist | Joined October 2021 | Twitter LinkedIn
Muninder Adavelli

Muninder Adavelli is a core team member and Digital Growth Strategist at Techjury. With a strong bac... | See full bio

April Grace Asgapo
Edited by
April Grace Asgapo

Editor

April Grace Asgapo
Joined June 2023 | LinkedIn
April Grace Asgapo

April is a proficient content writer with a knack for research and communication. With a keen eye fo... | See full bio

Techjury is supported by its audience. When you purchase through links on our site, we may earn an affiliate commission. Learn more.

JSON (Javascript Object Notation) is currently the most popular data transmission format. Almost 50% of the sites worldwide use this format. 

It is lightweight and formatted in such a way that is easily readable for humans and machines. JSON is also compatible with a lot of programming languages—including Python. 

This article will cover how to read and parse JSON files in Python with easy-to-understand examples. Keep reading to learn more.

Key Takeaways

  • JSON is a widely used format, compatible with various programming languages, even Python.
  • The json module in Python allows easy conversion between JSON data and Python dictionaries using loads() and load()functions for JSON string and file parsing.
  • Python dictionaries can be converted to JSON objects with the dumps() and dump() functions from the json module.
  • The load() function is particularly useful for reading larger JSON files, directly converting them into Python dictionaries.
  • Understanding the json module's capabilities in Python is essential for seamless data interchange between JSON and Python dictionaries.

Methods to Read and Parse JSON Data in Python

Parsing entails different tools and languages, depending on the format of data that needs to be parsed.  Luckily, JSON is a format that is compatible with most tools and programming languages. 

When reading or parsing JSON files using Python, the language supports JSON through the pre-installed module known as “json.” 

Python calls forth this module like this:

import json

The json module is capable of converting JSON strings or files into Python dictionaries and vice versa. Here is a table of JSON objects and their corresponding Python data types:

JSON

Python

Object

dict

Array

list, tuple

String

str

Number

int, float

Null

None

True

True

False

False

For JSON to be readable in Python, its objects must be converted to the corresponding Python data type.

Reading JSON for Python Dictionary Conversion

Reading a JSON file in Python always leads to an actual conversion from JSON objects to Python dictionaries. This is done by the functions load and loads (read as load-s or load string) in the json module.

JSON String to Python Dict

Here is an example of a JSON string:

{
  "name": "John Doe",
  "age": 30,
  "address": {
    "street": "123 Main Street",
    "city": "New York",
    "state": "NY"
  },
  "isPreferredCustomer": true,
  "notes": null
}

To convert this into a Python dict, use the loads() function. Here’s the script:

import json

# Example JSON string


json_string = """
{
  "name": "John Doe",
  "age": 30,
  "address": {
    "street": "123 Main Street",
    "city": "New York",
    "state": "NY"
  },
  "isPreferredCustomer": true,
  "notes": null
}

"""

python_dict = json.loads(json_string)
print(python_dict)
print(type(python_dict))

# Output

json_dict = {'name': 'John Doe', 'age': 30, 'address': {'street': '123 Main Street', 'city': 'New York', 'state': 'NY'}, 'isPreferredCustomer': True, 'notes': None}
<class 'dict'>

The JSON object is successfully converted to a Python dictionary. This is confirmed by the type() function, which printed the <class ‘dict’> result.

Reading JSON Files 

The same process is required when parsing a JSON file. To do that, you can employ the load() function. 

Say you have a JSON file named exampleuser.json that has the same content as the sample JSON string above.

To read this JSON file, you can: 

  1. Use the open() function in reading (‘r’) mode. 
  2. The load() function converts it into a Python dict
  3. The type() function confirms the data type.

import json

with open('exampleuser.json', 'r') as json_file:
    python_dict = json.load(json_file)
    print(python_dict)
    print(type(python_dict))

# Output

python_dict = {'name': 'John Doe', 'age': 30, 'address': {'street': '123 Main Street', 'city': 'New York', 'state': 'NY'}, 'isPreferredCustomer': True, 'notes': None}
<class 'dict'>

📝Note: This method is most useful in reading larger JSON files. 

Converting Python Dictionaries into JSON

Recall the capability of Python’s json module to convert dictionaries into JSON objects discussed earlier.

In this case, you will make use of the functions dump and dumps (read as dump-s or dump string).

Python Dict to JSON String

Use the dumps() function to convert Python dictionaries into JSON strings. Here is an example:

import json

python_dict = "{'name': 'John Doe', 'age': 30, 'address': {'street': '123 Main Street', 'city': 'New York', 'state': 'NY'}, 'isPreferredCustomer': True}"

json_string = json.dumps(python_dict)

print(json_string)
print(type(json_string))

# Output
json_string = "{'name': 'John Doe', 'age': 30, 'address': {'street': '123 Main Street', 'city': 'New York', 'state': 'NY'}, 'isPreferredCustomer': True}"
<class 'str'>

Conversion without data loss is a key advantage of JSON. To make it more readable, you can add the indent argument within the dumps() function.

json_string = json.dumps (python_dict, indent=4)

This should return a more readable output, like: 

{
  "name": "John Doe",
  "age": 30,
  "address": {
    "street": "123 Main Street",
    "city": "New York",
    "state": "NY"
  },
  "isPreferredCustomer": True,
}

Writing Python String into a JSON File

You have to use the dump() function to achieve this. Again, the open() function will open an existing file as indicated. 

If it does not exist, it will be automatically created with the help of the write (‘w’) mode. The write mode will also change the content of the file in case it does exist.

Here is a sample script:

import json

python_dict = "{'name': 'John Doe', 'age': 30, 'address': {'street': '123 Main Street', 'city': 'New York', 'state': 'NY'}, 'isPreferredCustomer': True}"

with open('exampleuser.json', 'w') as json_file:
    json.dump(python_dict, json_file)
    print(type(json_file))

Once done, you now know how to read and parse JSON using a Python module.

👍Helpful Article

Besides JSON, you can also parse other formats with Python. Try parsing HTML with RegEx using Python scripts. RegEx is a character sequence widely used in configuring strings of text. 

Conclusion

The JSON module is vital in providing a straightforward way of reading and parsing JSON—with just a few lines of code. 

However, this is nowhere near its full capabilities. Make sure to review the json module’s official documentation to dig for more.

FAQs.


How to get string data from JSON?

One way is to parse JSON with Python’s json module. You can make use of load and loads functions to read JSON objects. You can also specify the key-value pairs.

How to store a JSON file in Python?

Use the dump() function from the json module to write objects in a JSON file. You will also need the open() function in write mode to create a file or overwrite an existing one.

Is JSON easy to parse?

It is relatively easier to parse JSON than its alternative, XML. This is from the standpoint of programming languages—such as Python and Javascript. Another reason is JSON is lightweight, making it faster for parsers to work on. 

SHARE:

Facebook LinkedIn Twitter
Leave your comment

Your email address will not be published.