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

正文完