import json
dic = {"k1": "v1", "k2": "v2", "k3": None, "k4": False, "k5": {"name": "fhb", "age": "18"}}
# 将字典转换为json字符串
jd = json.dumps(dic, ensure_ascii=False)
print(jd)
print(type(jd))
# 将json字符串还原为dict
jl = json.loads(jd)
print(jl)
print(type(jl))
# 将json字符串写入文件
with open("fhb.json", mode="w", encoding="utf-8") as f1:
json.dump(dic, f1, ensure_ascii=False, indent=4)
"""
ensure_ascii: 数据不转换为ascii,中文存储的时候保持中文存储
indent: 保存文件之后数据格式化json的时候缩进等于4
"""
# 从文件读取json字符串
with open("fhb.json", mode="r", encoding="utf-8") as f2:
obj = json.load(f2)
print("obj -->", obj)
print("type(obj) -->", type(obj))
# 将对象存到json字符串中
class Car(object):
def __init__(self, name ,price):
self.name = name
self.price = price
c = Car("benz",1000)
# 方法一
p = json.dumps(c.__dict__, ensure_ascii=False)
print(p) # {"name": "benz", "price": 1000}
# 方法二
def func(obj):
return {
"name": obj.name,
"price": obj.price,
}
p = json.dumps(c, default=func)
print(p) # {"name": "benz", "price": 1000}
# 将json还原成对象
s = '{"name": "benz", "price": 1000}'
def func1(dict):
return Car(dict["name"],dict["price"])
p = json.loads(s ,object_hook=func1)
print(p.name,p.price) # benz 1000