Python JSON File Handling

JSON (JavaScript Object Notation) is a popular format for data exchange and is commonly used in web applications. Python provides a built-in json module to handle JSON data. In this tutorial, we will cover how to work with JSON files in Python, including reading, writing, and manipulating JSON data.

1. Importing the JSON Module

Before working with JSON data, you need to import Python’s built-in json module:

import json

Try It Now

2. Reading a JSON File

To read data from a JSON file, you can use the json.load() function. This function parses the JSON data from a file and returns it as a Python dictionary.

Example: Reading a JSON File

import json

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

Try It Now

In this example, we open the JSON file in read mode ('r') and use json.load() to parse the JSON data. The result is a Python dictionary that you can manipulate.

3. Writing to a JSON File

To write data to a JSON file, you can use the json.dump() function. This function takes a Python object and writes it to a file in JSON format.

Example: Writing to a JSON File

import json

data = {
    "name": "Alice",
    "age": 30,
    "city": "New York"
}

with open('output.json', 'w') as file:
    json.dump(data, file)

Try It Now

In this example, we use json.dump() to write a Python dictionary to a JSON file. The dictionary is converted into a JSON string before being written to the file.

4. Writing JSON with Pretty Formatting

By default, the JSON data written to a file is compact and not human-readable. To make it more readable, you can use the indent parameter in json.dump() to pretty-print the JSON data.

Example: Writing Pretty-Formatted JSON

import json

data = {
    "name": "Alice",
    "age": 30,
    "city": "New York"
}

with open('output_pretty.json', 'w') as file:
    json.dump(data, file, indent=4)

Try It Now

In this example, the indent=4 argument ensures that the JSON file is formatted with an indentation level of 4 spaces, making it more readable.

5. Converting JSON Data to Python Object

If you have a JSON string (not a file) that you want to convert into a Python object, you can use the json.loads() function. This function parses the JSON string and converts it into a Python dictionary.

Example: Converting JSON String to Python Object

import json

json_string = '{"name": "Alice", "age": 30, "city": "New York"}'
data = json.loads(json_string)
print(data)

Try It Now

Here, we use json.loads() to parse a JSON string and convert it into a Python dictionary.

6. Converting Python Object to JSON String

To convert a Python object (like a dictionary) into a JSON string, you can use the json.dumps() function. This is useful when you need to transmit JSON data over a network or save it as a string.

Example: Converting Python Object to JSON String

import json

data = {
    "name": "Alice",
    "age": 30,
    "city": "New York"
}

json_string = json.dumps(data)
print(json_string)

Try It Now

In this example, json.dumps() converts the Python dictionary into a JSON-formatted string.

7. Handling JSON Errors

When working with JSON data, it’s important to handle potential errors. Common errors include improperly formatted JSON and issues with file handling. You can catch these errors using a try-except block.

Example: Handling JSON Errors

import json

try:
    with open('invalid_data.json', 'r') as file:
        data = json.load(file)
except json.JSONDecodeError:
    print("Error: Invalid JSON format.")
except FileNotFoundError:
    print("Error: File not found.")

Try It Now

In this example, we catch a json.JSONDecodeError if the JSON data is invalid and a FileNotFoundError if the file doesn’t exist.

Conclusion

Python’s json module makes it easy to handle JSON data, whether you’re reading from or writing to JSON files, or converting between JSON and Python objects.