目录
json
小结:
pickle 模块
原文参考https://www.cnblogs.com/yyds/p/6563608.html
import json
import demjson as demjson
data = {"a": "str", "c": True, "b": 11.1, "e": 10, "d": None, "g": [4, 5, 6], "f": [1, 2, 3]}
# ddata = json.dumps(data,sort_keys=True, separators=(',', ':'),indent=4)
# ldata = json.loads(str(data)) # 报错,提示要用双引号,因为str()后,结果是k、v都是单引号
# print(ldata)
sddata = json.dumps(str(data))
print(sddata) # "{'a': 'str', 'c': True, 'b': 11.1, 'e': 10, 'd': None, 'g': [4, 5, 6], 'f': [1, 2, 3]}"
# 如果字符串本身的key、value是单引号,怎么解决
# 方法1行不通,因为json.loads(Json),Json必须使用符合json规则,True为true,None为null
s = str(data).replace("'",'"')
# print(s,type(s)) # {"a": "str", "c": True, "b": 11.1, "e": 10, "d": None, "g": [4, 5, 6], "f": [1, 2, 3]}
# print(json.loads(s))
s1 = '{"a": "str", "c": true, "b": 11.1, "e": 10, "d": null, "g": [4, 5, 6], "f": [1, 2, 3]}'
print(json.loads(s1))
# 方法2
print(demjson.encode(str(data))) # "{'a': 'str', 'c': True, 'b': 11.1, 'e': 10, 'd': None, 'g': [4, 5, 6], 'f': [1, 2, 3]# }"
# dump() load()
with open(os.path.join(os.path.dirname(__file__),'test.json'),'w') as fp:
json.dump({'a': '中国', 'c': True, 'e': 10, 'b': 11.1, 'd': None, 'f': [1, 2, 3], 'g': (4, 5, 6)}, fp,indent=4)
with open(os.path.join(os.path.dirname(__file__),'test.json'),'r') as fp:
print(json.load(fp))
# encode() decode()
str1 = '中国'
str2 = str1.encode()
str3 = str2.decode()
print(str1,str2,str3)
# 1编写转换函数
def obj2dict(obj):
d = {}
# print(obj.__class__.__name__) # Student
# print(obj.__module__) # __main__
# print(obj.__dict__) # {'sno': 1, 'age': 19, 'name': 'xh'}
d['__class__'] = obj.__class__.__name__
d['__module__'] = obj.__module__
d.update(obj.__dict__) # 添加到指定字典dict里的字典
return d
def dict2obj(d):
if '__class__' in d:
class_name = d.pop('__class__')
module_name = d.pop('__module__')
module = __import__(module_name)
class_ = getattr(module, class_name)
args = dict((key.encode('ascii'), value) for key, value in d.items())
instance = class_(**args)
else:
instance = d
return instance
print((obj2dict(stu)))
json.dumps(obj2dict(stu))
print(json.dumps(stu,default=obj2dict)) # default,把obj转化成obj2dict
with open(os.path.join(os.path.dirname(__file__),'test.json'),'w') as fp:
json.dump(obj2dict(stu),fp,indent=4)
json.loads(xxx),将json反序列化成python的数据对象,但是使用时,必须确保xxx符合json规则
例如python True,json是true
k、v要用双引号
json.dumps(xxx),将xxx序列化成json,以便网络传输,或者存储到磁盘文件
json.dump(xxx),将xxx序列化成json,直接网络传输,或者存储到磁盘文件
json.load(xxx),可直接从文件读取json反序列化成python的数据对象