How to Read and Write JSON Files in Python

Handling data efficiently is a crucial part of modern programming, and JSON (JavaScript Object Notation) has become the go-to format for data interchange across platforms and languages. When dealing with APIs, configurations, or data storage, knowing how to manage JSON Files in Python is an essential skill for every developer.

JSON is lightweight, human-readable, and supported by nearly every programming environment, making it far more flexible than formats like XML or CSV in many scenarios. Understanding how to read and write JSON files in Python helps you easily exchange structured information while keeping your code clean and maintainable.

The json Module in Python

Python makes working with JSON incredibly simple through the it’s built-in json module. This module allows you to read, write, parse, and convert JSON data directly into Python objects such as dictionaries and lists. The most useful functions provided by this module include:

  • json.load() – reads JSON data from a file
  • json.loads() – reads JSON data from a string
  • json.dump() – writes JSON data to a file
  • json.dumps() – writes JSON data to a string

These methods make it easy to transform between Python’s data structures and JSON’s textual representation without manual parsing.

Reading JSON Data in Python

There are three main ways to get JSON data in Python. You can load it from a file stored on your system, receive it as a string within your program, or fetch it from an API response when communicating with web services. These are the most common sources when handling JSON Files in Python.

Loading JSON Data From File In Python

When working with stored data such as configuration files, it’s common to read from a .json file. You can python read json file easily using json.load() as shown below:

import json

with open("data.json", "r") as file:
    data = json.load(file)

print(data)

Output:

{'name': 'John', 'age': 28, 'skills': ['Python', 'Data Analysis']}

Here, json.load() automatically converts JSON formatted text into a Python dictionary or list, depending on the structure. Now you can interact with the data just like any other Python object. For instance, if data.json contains details of users or settings, you can access and manipulate them effortlessly.

Loading JSON Data From String In Python

APIs or web responses often send data as JSON strings. The json.loads() function helps python parse json strings into Python-native objects easily.

json_string = """
{
    "name": "Alice",
    "age": 25,
    "hobbies": [
        "reading",
        "coding"
    ]
}
"""
data = json.loads(json_string)

print(data)

Output:

{'name': 'Alice', 'age': 25, 'hobbies': ['reading', 'coding']}

This approach is useful when data isn’t saved in a file but comes as a response from an API or a message queue. You can now use the data variable as a normal Python object and process it for analysis, visualization, or other operations.

Writing JSON Data in Python

Saving data back to a file is just as simple. The python write json file process uses json.dump() to take a Python dictionary or list and write it to a .json file. This ensures your data is in proper JSON format and can be easily read by other applications or systems that understand JSON.

import json

data = {"name": "Bob", "age": 30, "hobbies": ["photography", "cycling"]}
with open("output.json", "w") as file:
    json.dump(data, file)

Generated output.json file content:

{"name": "Bob", "age": 30, "hobbies": ["photography", "cycling"]}

Sometimes, you might not want to write directly to a file but need a JSON string. In this type of case, use json.dumps() to share data via API or response.

import json

data = {"product": "Laptop", "price": 1200, "available": True}
json_output = json.dumps(data)

The python json dump and python json dumps functions give you full control over how to output your structured data, whether for storage, display, or communication between systems.

Making JSON Readable with Pretty Printing

By default, JSON outputs appear in a single line, which isn’t pleasant to read. To enhance readability, you can use the indent parameter in json.dump() or json.dumps().

import json

data = {"city": "New York", "population": 8800000, "famous_for": ["Broadway", "Finance"]}
print(json.dumps(data, indent=4))

Output:

{
    "city": "New York",
    "population": 8800000,
    "famous_for": [
        "Broadway",
        "Finance"
    ]
}

This produces neatly formatted and indented JSON text, often used in logs, configuration files, or debugging scenarios. Pretty-printing makes large data structures easy to understand and maintain, which is especially helpful when collaborating on projects.

When working with JSON Files in Python, always make sure your data is valid and well-formed to avoid errors. Use with statements for safe file handling and keep your data types consistent between Python and JSON. Handle encoding properly, especially with multilingual content, and use indentation to make files more readable. For large datasets, consider compressed or binary formats and remember to python parse json efficiently for better performance.

Conclusion

Mastering how to read and write JSON Files in Python is one of the most useful skills for handling real-world data. From web APIs to configuration files, JSON simplifies the exchange of information and enhances interoperability across systems.

If you enjoyed learning about handling JSON Files in Python, you might also like our detailed guide on How to Generate QR Code in Python Using Segno. It’s a practical read that shows how to create dynamic QR codes efficiently using a lightweight Python library.