更新時(shí)間:2023年03月29日11時(shí)25分 來源:傳智教育 瀏覽次數(shù):
當(dāng) Python 字典和JSON字符串的鍵或值為自定義對(duì)象時(shí),需要進(jìn)行特殊處理才能進(jìn)行轉(zhuǎn)換。以下是兩個(gè)示例:
1.自定義對(duì)象轉(zhuǎn) JSON 字符串
假設(shè)有一個(gè)自定義對(duì)象Person,其中包含name、age和city三個(gè)屬性:
class Person: def __init__(self, name, age, city): self.name = name self.age = age self.city = city
我們可以將這個(gè)對(duì)象轉(zhuǎn)換為一個(gè)Python字典,然后再將其轉(zhuǎn)換為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 字符串轉(zhuǎn)自定義對(duì)象
假設(shè)有以下 JSON 字符串:
{ "name": "Alice", "age": 30, "city": "New York" }
我們可以使用json模塊中的loads()函數(shù)將其轉(zhuǎn)換為Python字典,然后再將其轉(zhuǎn)換為自定義對(duì)象:
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
需要注意的是,當(dāng)Python對(duì)象嵌套了其他自定義對(duì)象或容器對(duì)象時(shí),轉(zhuǎn)換起來會(huì)更加復(fù)雜。這時(shí)需要使用遞歸或其他的轉(zhuǎn)換方法。
北京校區(qū)