JSON字符串与字典互相转换
[
{
"name": "iPhone9",
"price": 9999,
"count": 3000
},
{
"name": "Tesla",
"price": 800000,
"count": 122
}
]
import json
data = {'name': 'Alex', 'company': 'Google', 'age': 34}
# 将字典转换为JSON字符串
jsonStr = json.dumps(data)
print(type(jsonStr)) #
print(jsonStr) # {"name": "Alex", "company": "Google", "age": 34}
# 从json文件读取数据转换为字典
with open('products.json', 'r') as f:
jsonStr = f.read()
j_obj = json.loads(jsonStr)
print(type(j_obj)) #
for k in j_obj:
print(type(k)) #
for key, val in k.items():
print("%s --> %s" % (key, val))
类实例列表与JSON字符串互相转换(json文件数据同上)
class Product:
def __init__(self, dic):
self.__dict__ = dic
f = open('products.json', 'r')
jsonStr = f.read()
# 将JSON字符串转换为Product对象列表
products = json.loads(jsonStr, object_hook=Product)
for p in products:
print('name = ', p.name)
print('price = ', p.price)
print('count = ', p.count)
f.close()
# 定义将Product对象转换为字典的函数
def product2dict(product):
return {
'name': product.name,
'price': product.price,
'count': product.count
}
# 将Product对象列表转换为JSON字符串
jsonStr = json.dumps(products, default=product2dict, ensure_ascii=False)
print(jsonStr)