SoFunction
Updated on 2025-03-04

From basic to advanced, you can play JSON in Python

Processing JSON data in Python is one of the common tasks in daily development. JSON (JavaScript Object Notation) is a lightweight data exchange format that has been widely used in many fields such as web development and data storage. This article will introduce in detail how to process JSON objects in Python, including basic operations, data operations, advanced operations, file and directory operations, performance optimization, etc., and display applications in different scenarios through specific code examples.

1. Basic operations

1. Convert Python objects to JSON string

In Python, we can use the json module to convert Python objects (such as dictionaries, lists, etc.) into JSON format strings. This operation is often used to prepare data for transfer to a web service or to save it as a JSON file.

import json
# Python Dictionaryperson = {
    'name': 'Liu Jie',
    'age': 29,
    'city': 'Shanghai'
}
# Convert Python dictionary to JSON stringjson_string = (person, ensure_ascii=False)
print("Python object converted to JSON string:")
print(json_string)

In this code, we convert a dictionary named person to a JSON string. ensure_ascii=False ensures that non-ASCII characters (such as Chinese) can be displayed normally.

2. Parsing JSON strings into Python objects

It is common to parse JSON strings as Python objects, especially when processing JSON data obtained from a web interface or file.

# JSON stringjson_string = '{"name": "Chen Hui", "age": 34, "city": "Beijing"}'
# Parsing JSON strings into Python dictionarydata = (json_string)
print("JSON string parses into Python objects:")
print(data)

This code shows how to convert JSON strings into Python dictionary objects for easy subsequent processing.

3. Write Python objects to JSON file

Save Python objects as JSON files, usually used for data storage or sharing.

# Python Dictionaryperson = {
    'name': 'Sun Yang',
    'age': 25,
    'city': 'Chengdu'
}
# Write Python dictionary to JSON filewith open('person_data.json', 'w', encoding='utf-8') as f:
    (person, f, ensure_ascii=False)
print("Python object has been written to a JSON file")

The above code writes a dictionary to a file named person_data.json.

4. Read Python objects from JSON files

Read the JSON data stored in the file and parse it into a Python object.

# Read Python dictionary from JSON filewith open('person_data.json', 'r', encoding='utf-8') as f:
    data = (f)
print("Python object has been read from JSON file:")
print(data)

This code shows how to read a JSON file and parse it into a Python dictionary.

2. Data operation

1. Modify the data in the JSON file

Sometimes we need to modify the data in the JSON file. The following example demonstrates how to read a file, modify data, and write it back to a file.

# Read Python dictionary from JSON filewith open('person_data.json', 'r', encoding='utf-8') as f:
    data = (f)
# Modify datadata['age'] = 30
# Write the modified data back to the JSON filewith open('person_data.json', 'w', encoding='utf-8') as f:
    (data, f, ensure_ascii=False)
print("Modified data in JSON file and saved")

2. Merge two JSON files

If you need to merge the data of two JSON files, you can first read the two files, then merge their contents, and finally write them to a new file.

# Read the first JSON filewith open('', 'r', encoding='utf-8') as f:
    data1 = (f)
# Read the second JSON filewith open('', 'r', encoding='utf-8') as f:
    data2 = (f)
# Merge two dictionariescombined_data = {**data1, **data2}
# Write the merged data to a new JSON filewith open('combined_data.json', 'w', encoding='utf-8') as f:
    (combined_data, f, ensure_ascii=False)
print("Two JSON files have been merged and saved")

3. Add new key-value pairs

Add new key-value pairs to existing JSON data.

# Read Python dictionary from JSON filewith open('person_data.json', 'r', encoding='utf-8') as f:
    data = (f)
# Add new key-value pairsdata['job'] = 'programmer'
# Write the updated data back to the JSON filewith open('person_data.json', 'w', encoding='utf-8') as f:
    (data, f, ensure_ascii=False)
print("New key-value pairs have been added and saved")

4. Delete key-value pairs

If you need to delete a key-value pair from JSON data, you can use the del statement.

# Read Python dictionary from JSON filewith open('person_data.json', 'r', encoding='utf-8') as f:
    data = (f)
# Delete key-value pairsdel data['city']
# Write the updated data back to the JSON filewith open('person_data.json', 'w', encoding='utf-8') as f:
    (data, f, ensure_ascii=False)
print("Deleted key-value pairs and saved")

3. Advanced operation

1. Format output JSON string

If you need to output a JSON string in a more readable format, you can use the indent parameter to format the output.

# Python Dictionaryperson = {
    'name': 'Wu Hao',
    'age': 24,
    'city': 'Xiamen'
}
# Format output JSON stringjson_string = (person, indent=4, ensure_ascii=False)
print("Format output JSON string:")
print(json_string)

2. Handle nested JSON structures

In JSON, nested structures are very common. We can handle such a structure and convert it to a JSON string.

#Nested Python dictionarynested_person = {
    'name': 'Zhao Qiang',
    'details': {
        'age': 30,
        'city': 'Wuhan'
    }
}
# Convert nested Python dictionary to JSON stringjson_string = (nested_person, ensure_ascii=False)
print("Convert nested JSON structure to JSON string:")
print(json_string)

4. Post-school summary

When processing JSON data, Python's json module provides many convenient functions, covering the parsing of transitions from simple objects to complex nested structures. Through the examples in this tutorial, you can flexibly use Python to convert, store, modify, merge JSON data.

The following things should be paid attention to when processing json format data:

1. When dealing with JSON containing non-ASCII characters (such as Chinese), it is recommended to use ensure_ascii=False, otherwise you may encounter character encoding problems.

2. When operating files, please make sure that the file path is correct and close the file in time after the operation is completed to avoid file corruption.

3. When merging multiple JSON files, make sure the data structure is consistent to avoid data overwriting or loss.

4. By mastering these techniques, you will be able to use JSON data to perform various operations more efficiently in Python projects.

This is the article about taking you to play JSON in Python from basics to advanced. For more related Python JSON content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!