SoFunction
Updated on 2025-04-11

Python uses json module to read and write JSON data

In modern software development, JSON (JavaScript Object Notation) has become one of the most popular data exchange formats. Python provides a built-in json module, which allows us to easily parse JSON data (read) and generate JSON data (write). Whether it is Web API interaction, configuration file storage, or data serialization, the json module is an indispensable tool. This article will introduce in detail the operation of the json module reading, writing, formatting, encoding and decoding, etc., and display its application in combination with actual cases.

1. Mapping relationship between JSON and Python data types

Python's json module can convert between Python basic data types and JSON data types, and the mapping relationship is as follows:

Python Types JSON Type Example
dict object {"name": "Alice", "age": 25}
list / tuple array ["apple", "banana", "cherry"]
str string "hello"
int / float number 42, 3.14
bool true / false true, false
None null null

2. Read JSON data

Python can read JSON data from a string or a file.

2.1 Parsing from JSON strings

import json

json_str = '{"name": "Alice", "age": 25, "city": "New York"}'

# Convert JSON strings to Python dictionarydata = (json_str)

print(data["name"])  # Output: Aliceprint(type(data))    # Output: <class 'dict'>

() Function:

  • Input: A string in JSON format.
  • Output: Convert to a Python dict object.

2.2 Reading from JSON files

Suppose there is a file:

{
    "name": "Bob",
    "age": 30,
    "skills": ["Python", "Java", "C++"]
}

Use () to read the file:

with open("", "r", encoding="utf-8") as file:
    data = (file)

print(data["name"])   # Output: Bobprint(data["skills"]) # Output: ['Python', 'Java', 'C++']

() Function:

  • Enter: JSON file object.
  • Output: Python dict object.

3. Write JSON data

Python can write data to a string or file.

3.1 Convert Python objects to JSON strings

import json

data = {
    "name": "Charlie",
    "age": 28,
    "city": "San Francisco"
}

# Convert Python dictionary to JSON stringjson_str = (data)

print(json_str)
print(type(json_str))  # Output: <class 'str'>

() Function:

  • Input: Python dict, list, str, etc.
  • Output: A string in JSON format.

3.2 Write Python objects to JSON files

import json

data = {
    "name": "David",
    "age": 35,
    "languages": ["Python", "Go", "Rust"]
}

# Write to JSON filewith open("", "w", encoding="utf-8") as file:
    (data, file)

print("Data has been written")

() Function:

  • Input: Python dict (or other serializable object).
  • Output: Write to a JSON file.

4. JSON format output (indent, sort)

By default, JSON generated strings are compact and not easy to read:

data = {"name": "Eve", "age": 26, "city": "Paris"}
json_str = (data)

print(json_str)  # Output: {"name": "Eve", "age": 26, "city": "Paris"}

To output JSON more clearly, you can use the indent parameter:

json_str = (data, indent=4)
print(json_str)

Output (Format JSON):

{
    "name": "Eve",
    "age": 26,
    "city": "Paris"
}

If you want to sort the key name:

json_str = (data, indent=4, sort_keys=True)
print(json_str)

Output (key sort):

{
    "age": 26,
    "city": "Paris",
    "name": "Eve"
}

5. Handle JSON encoding and decoding (object serialization)

If the JSON data contains custom objects, the default () cannot be processed:

import json
from datetime import datetime

data = {"name": "Alice", "time": ()}

# An error will be reported: Object of type datetime is not JSON serializablejson_str = (data)

You can use the default parameter to convert the datetime object to a string:

def json_serial(obj):
    if isinstance(obj, datetime):
        return ()  # Convert to ISO 8601 time format    raise TypeError("Type not serializable")

json_str = (data, default=json_serial, indent=4)
print(json_str)

Sample output:

{
    "name": "Alice",
    "time": "2024-02-04T14:00:00.123456"
}

6. Handle JSON parsing errors

When parsing JSON, you may encounter a format error:

import json

invalid_json = '{"name": "Tom", "age": 30,}'  # There is a comma at the end
try:
    data = (invalid_json)
except  as e:
    print(f"JSON Parsing error: {e}")

Output:

JSON parsing error: Expecting property name enclosed in double quotes

7. Best Practices for Reading and Writing of JSON

Use try-except to catch exceptions when reading JSON

try:
    with open("", "r", encoding="utf-8") as file:
        config = (file)
except (FileNotFoundError, ) as e:
    print(f"mistake: {e}")

Use indent=4 when writing to JSON to make data easier to read

(data, file, indent=4)

When processing non-standard data types, use default for serialization

(data, default=json_serial)

8. Conclusion

operate method
Read JSON from a string (json_str)
Read JSON from a file (file)
Convert Python objects to JSON strings (obj)
Write Python objects to JSON files (obj, file)
Format JSON (Indent) (obj, indent=4)
Parsing error handling
Handle non-standard data types default=json_serial

Python'sjsonModules provide powerful and easy-to-use JSON processing capabilities. Using these methods reasonably can make your code more efficient and maintainable!

The above is the detailed content of Python using the json module to read and write JSON data. For more information about Python reading and writing JSON data, please pay attention to my other related articles!