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)
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'}}
嵌套的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"}}