程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python | JSON (Dict) and Class conversion

編輯:Python

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與JSONString conversion method can directly use the system before,如下

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. 使用內置方法

DictNested occurs not in line with expectations.

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"}}

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved