1. 前言
J S O N ⇔ D i c t ⇔ C l a s s {JSON}\Leftrightarrow{Dict}\Leftrightarrow{Class} JSON⇔Dict⇔Class
这里主要讲的是Dict与Class转换,至于Dict与JSON字符串之前转换可以直接使用系统方法,如下
import json
d = {'name': 'yimt', 'age': 123, 'detail': {'phone': '123456789'}}
# Dict->JSON Str
s: str = json.dumps(d)
# JSON Str->Dict
d = json.loads(s)
2. 使用内置方法
Dict嵌套时会出现不符合预期的情况。
class Detail:
phone: str
def __str__(self):
return f'phone={self.phone}'
class Person:
name: str
age: int
detail: Detail
def __str__(self):
return f'name={self.name}, age={self.age}, detail=Detail({self.detail})'
if __name__ == '__main__':
d = {'name': 'yimt', 'age': 123, 'detail': {'phone': '123456789'}}
p: Person = Person()
# Dict -> Class
p.__dict__ = d
print(p) # Output: name=yimt, age=123, detail=Detail({'phone': '123456789'})
# Class -> Dict
print(p.__dict__) # Output: {'name': 'yimt', 'age': 123, 'detail': {'phone': '123456789'}}
3. pydantic
嵌套的Dict转Class,Class转Dict
from pydantic import BaseModel
class Detail(BaseModel):
phone: str
def __str__(self):
return f'phone={self.phone}'
class Person(BaseModel):
name: str
age: int
detail: Detail
def __str__(self):
return f'name={self.name}, age={self.age}, detail=Detail({self.detail})'
if __name__ == '__main__':
d = {'name': 'yimt', 'age': 123, 'detail': {'phone': '123456789'}}
# Dict -> Class
p: Person = Person(**d)
print(p) # name=yimt, age=123, detail=Detail(phone=123456789)
# Class -> Dict
print(p.json()) # Output: {"name": "yimt", "age": 123, "detail": {"phone": "123456789"}}