更新时间:2023年03月29日11时25分 来源:传智教育 浏览次数:
当 Python 字典和JSON字符串的键或值为自定义对象时,需要进行特殊处理才能进行转换。以下是两个示例:
1.自定义对象转 JSON 字符串
假设有一个自定义对象Person,其中包含name、age和city三个属性:
class Person:
def __init__(self, name, age, city):
self.name = name
self.age = age
self.city = city
我们可以将这个对象转换为一个Python字典,然后再将其转换为JSON字符串:
import json
person = Person("Alice", 30, "New York")
person_dict = {"name": person.name, "age": person.age, "city": person.city}
person_json = json.dumps(person_dict)
print(person_json)
输出:
{"name": "Alice", "age": 30, "city": "New York"}
2.JSON 字符串转自定义对象
假设有以下 JSON 字符串:
{
"name": "Alice",
"age": 30,
"city": "New York"
}
我们可以使用json模块中的loads()函数将其转换为Python字典,然后再将其转换为自定义对象:
import json
class Person:
def __init__(self, name, age, city):
self.name = name
self.age = age
self.city = city
person_json = '{"name": "Alice", "age": 30, "city": "New York"}'
person_dict = json.loads(person_json)
person = Person(person_dict["name"], person_dict["age"], person_dict["city"])
print(person.name, person.age, person.city)
输出:
Alice 30 New York
需要注意的是,当Python对象嵌套了其他自定义对象或容器对象时,转换起来会更加复杂。这时需要使用递归或其他的转换方法。