1. 将一个对象转换为对应的json字符串
import json
class Product:
def __init__(self, name, price, count):
self.name = name
self.price = price
self.count = count
product = Product('特斯拉', 1000000, 20)
def product2Dict(obj):
return {
'name': obj.name,
'price':obj.price,
'count':obj.count
}
jsonStr = json.dumps(product, default=product2Dict, ensure_ascii=False)
print(jsonStr)
{"name": "特斯拉", "price": 1000000, "count": 20}
2. 将对象列表转换为json数组
f = open('products.json', 'r', encoding='utf-8')
jsonStr = f.read()
f.close()
class Product:
def __init__(self, d):
self.__dict__ = d
products = json.loads(jsonStr, object_hook=Product)
print(products)
for product in products:
print(product.name)
jsonStr = json.dumps(products, default=product2Dict, ensure_ascii=False)
print(type(jsonStr))
print(jsonStr)
[<__main__.Product object at 0x00000161832F02E8>, <__main__.Product object at 0x00000161832F0FD0>]
iPhone9
特斯拉
<class 'str'>
[{"name": "iPhone9", "price": 9999, "count": 3000}, {"name": "特斯拉", "price": 800000, "count": 122}]
正文完