Application of JSON data processing in Python for python learning: from parsing to generation

JSON file is a lightweight data exchange format that uses a structure similar to JavaScript syntax to facilitate data exchange between different platforms and programming languages. In Python, we can use the built-in json module to read and write JSON files.

Here is a simple example showing how to read and write JSON files using the json module in Python:

import json  
  
# 读取JSON文件  
with open('data.json', 'r') as f:  
    data = json.load(f)  
  
# 打印JSON数据  
print(data)  
  
# 修改JSON数据  
data['name'] = 'Alice'  
data['age'] = 30  
  
# 写入JSON文件  
with open('data.json', 'w') as f:  
    json.dump(data, f)

Insert image description here

In this example, we first read a JSON file named data.json using the json.load() function and stored the data in the data variable. Then, we printed the JSON data we read. Next, we modified two fields in the JSON data and used the json.dump() function to write the modified data back to the same file.

In addition to basic read and write operations, the json module provides many other functions, such as:

Use the json.dumps() function to serialize Python objects into JSON strings.
Use the json.loads() function to deserialize a JSON string into a Python object.
Use the json.dump() and json.dumps() functions for more flexible writing operations (such as writing to different file objects, writing to different encoding formats, etc.).
Use the json.load() and json.loads() functions for more flexible reading operations (such as reading different file objects, reading different encoding formats, etc.).
You can use the sort_keys parameter in the json.dump() and json.dumps() functions to sort the output.
You can use the default parameter to specify a function that is used to handle Python objects that cannot be serialized.

Here's an example showing how to use these features:

import json  
  
# 定义一个自定义的数据类型  
class Person:  
    def __init__(self, name, age):  
        self.name = name  
        self.age = age  
  
# 将自定义数据类型转换为JSON字符串  
person = Person('Bob', 25)  
json_str = json.dumps(person.__dict__, default=str)  
print(json_str)  # 输出:"{\"name\": \"Bob\", \"age\": 25}"

How to parse a JSON string into a Python data structure:

import json  
  
# JSON字符串  
json_str = '{"name": "Alice", "age": 30, "city": "New York"}'  
  
# 将JSON字符串解析为Python数据结构  
data = json.loads(json_str)  
  
# 输出解析后的Python数据结构  
print(data)  # 输出:{'name': 'Alice', 'age': 30, 'city': 'New York'}

Processing JSON data containing nested structures usually requires a recursive approach. In Python, we can use recursive functions to handle such nested structures.
Here is a Python example for processing nested structured JSON data:

First, assume we have the following JSON data:

{  
  "name": "John",  
  "age": 30,  
  "address": {  
    "street": "123 Main St",  
    "city": "New York",  
    "state": "NY",  
    "postalCode": "10001"  
  },  
  "phoneNumbers": [  
    {  
      "type": "home",  
      "number": "555-555-1234"  
    },  
    {  
      "type": "office",  
      "number": "555-555-5678"  
    }  
  ]  
}

We can create a Python function to handle this nested JSON structure:

import json  
  
def process_json(data):  
    for key, value in data.items():  
        if isinstance(value, dict):  
            print(f"Nested dictionary found for key: {
      
      key}")  
            nested_data = process_json(value)  
            # Process the nested data here, for example, print it out  
            print(f"Processed nested data: {
      
      nested_data}")  
        elif isinstance(value, list):  
            print(f"Nested list found for key: {
      
      key}")  
            nested_list = [process_json(item) for item in value if isinstance(item, dict)]  
            # Process the nested list here, for example, print it out  
            print(f"Processed nested list: {
      
      nested_list}")  
        else:  
            # Process the non-nested data here, for example, print it out  
            print(f"Processing non-nested data: {
      
      value}")  
    return data  # Return the processed data (can be modified before returning)

You can handle nested JSON structures by calling this function and passing in your JSON data:

python
json_data = {
    
     ... }  # Your JSON data here  
processed_data = process_json(json_data)

This function will recursively check each element in the data, and if it is a dictionary, then the function will recursively process the dictionary. If it is a list, the function checks each element in the list, if the element is a dictionary, the function processes the dictionary recursively. For non-nested data, you can add the processing logic you need in the function.
Insert image description here

In addition, you can customize JSON serialization and deserialization by implementing two special methods, json() and from_json() change.

Suppose we have a class Person:

class Person:  
    def __init__(self, name, age):  
        self.name = name  
        self.age = age
我们可以定义 __json__() 方法来控制如何将对象转换为 JSON 字符串:

python
class Person:  
    def __init__(self, name, age):  
        self.name = name  
        self.age = age  
  
    def __json__(self):  
        return {
    
      
            'name': self.name,  
            'age': self.age,  
        }

In the above code, json() method returns a dictionary, which is the data structure we usually use to serialize JSON . When we convert the Person object to a JSON string, Python will call the json() method.

On the other hand, we can control how a JSON string is deserialized into an object by implementing the from_json() method:

class Person:  
    def __init__(self, name, age):  
        self.name = name  
        self.age = age  
  
    def __json__(self):  
        return {
    
      
            'name': self.name,  
            'age': self.age,  
        }  
  
    @classmethod  
    def from_json(cls, json):  
        return cls(json['name'], json['age'])

In the above code, the from_json() method accepts a dictionary as a parameter and then uses this dictionary to create a new Person object. When we deserialize a JSON string into a Person object, Python will call the from_json() method.

Note that the from_json() method needs to be a class method, which means you need to use the @classmethod decorator. Additionally, you need to include the class itself (i.e. cls) as an argument to the from_json() method.

Guess you like

Origin blog.csdn.net/u014740628/article/details/134823700