41 - 將json字符串轉換爲類的實例

如何將一個json文檔映射爲對象

product.json

{"name":"iPhone9",
"price":9999,
"count":3000}
import json

class Product:
    def __init__(self, d):
        self.__dict__ = d
        
f = open('product.json', 'r')
jsonStr = f.read()
print(jsonStr)

product = json.loads(jsonStr, object_hook=Product)
print(type(product))
# print(product['name'])
print(product.name)
print(product.price)
{"name":"iPhone9",
"price":9999,
"count":3000}
<class '__main__.Product'>
iPhone9
9999
def json2Product(d):
    return Product(d)

# 指定一個轉換函數
product1 = json.loads(jsonStr, object_hook=json2Product)
print(product1.name)
print(product1.price)
iPhone9
9999

42 - 將類的實例轉換爲json字符串

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章