Menu
CoddyTech

自定义 JSON 解码

Coddy Python JSON 课程的第 9 课,共 9 课。

自定义 JSON 解码是 Python json 模块的一项高级功能,可以让你控制 JSON 数据如何转换为 Python 对象。在处理复杂数据结构,或想从 JSON 数据创建特定的 Python 对象时,这项功能尤其有用。

JSONDecoder 类

要实现自定义 JSON 解码,你需要继承 json.JSONDecoder 类并重写它的 object_hook 方法:


import json

class CustomDecoder(json.JSONDecoder):
    def object_hook(self, dct):
        # 在这里编写自定义解码逻辑
        return dct

使用自定义解码器

定义好自定义解码器后,你就可以将它用于 json.loads() 或 json.load():


decoded_object = json.loads(json_string, cls=CustomDecoder)

示例:解码为自定义对象

来看一个实际示例,了解如何将 JSON 数据解码为自定义 Python 对象:


import json
from datetime import datetime

class Person:
    def __init__(self, name, birthdate):
        self.name = name
        self.birthdate = birthdate

class CustomDecoder(json.JSONDecoder):
    def object_hook(self, dct):
        if 'name' in dct and 'birthdate' in dct:
            return Person(dct['name'], datetime.fromisoformat(dct['birthdate']))
        return dct

json_string = '{"name": "Alice", "birthdate": "1990-05-15"}'
person = json.loads(json_string, cls=CustomDecoder)

print(type(person))  # 输出:<class '__main__.Person'>
print(person.name)   # 输出:Alice
print(person.birthdate)  # 输出:1990-05-15 00:00:00

要点

  • 每解码一个对象,都会调用一次 object_hook 方法。
  • 你可以检查特定的键或模式,以确定如何解码对象。
  • 如果无需对特定结构进行自定义解码,就按原样返回对象。
  • 自定义解码器适合直接从 JSON 数据创建特定领域的对象。

使用自定义 JSON 解码器,可以将 JSON 数据无缝集成到 Python 应用程序的对象模型中,使数据反序列化更加灵活,也更符合你的具体需求。

quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

challenge icon

挑战

简单

为天气数据系统创建一个自定义 JSON 解码器。解码器应将 JSON 字符串转换为具有特定属性和转换规则的 WeatherData 对象。请实现以下功能:

  1. 定义一个 WeatherData 类,包含以下属性:location、temperature、humidity 和 conditions。
  2. 创建一个自定义的 JSONDecoder 子类,实现以下功能:
    • 将温度从华氏度转换为摄氏度,并四舍五入到小数点后一位。
    • 确保湿度以百分比表示(例如,0.65 变为 65%)。
    • 将 conditions 字符串中的每个单词首字母大写。
  3. 实现一个函数,该函数接收 JSON 字符串,使用自定义解码器解析它,并返回包含天气数据的格式化字符串。

将提供以下输入:


{"location": "new york", "temperature": 72, "humidity": 0.65, "conditions": "partly cloudy"}

按以下格式打印格式化后的字符串:

"Location: [location], Temperature: [temp]°C, Humidity: [humidity], Conditions: [conditions]"

亲手试试

Here's a suitable starter code for the challenge:

```python
import json

# Read input
json_string = input()

class WeatherData:
    def __init__(self, location, temperature, humidity, conditions):
        self.location = location
        self.temperature = temperature
        self.humidity = humidity
        self.conditions = conditions

class CustomJSONDecoder(json.JSONDecoder):
    def __init__(self, *args, **kwargs):
        json.JSONDecoder.__init__(self, object_hook=self.object_hook, *args, **kwargs)

    def object_hook(self, dct):
        # TODO: Implement the custom decoding logic here
        pass

def parse_weather_data(json_string):
    # TODO: Implement the parsing function here
    pass

# TODO: Use the CustomJSONDecoder and parse_weather_data function to process the input

# Placeholder for the result
result = "Location: [location], Temperature: [temp]°C, Humidity: [humidity], Conditions: [conditions]"

# Output the result
print(result)
```

Python JSON中的所有课

自己练习: Python 在线编译器