python-json的用法,,使用json的两种场


使用json的两种场景:
1:网络传输中使用
2,文件读写的时候使用

json用法的几个特点:
dumps ,loads在内存中操作
dump,load 在文件中操作



json 在所有的语言之间都通用 : json序列化的数据 在python上序列化了 那在java中也可以反序列化
能够处理的数据类型是非常有限的 : 字符串 列表 字典 数字
字典中的key只能是字符串

如下面几种用法就会出错
# 问题1  错把数字转成字符串# dic = {1 : ‘value‘,2 : ‘value2‘}# ret = json.dumps(dic)  # 序列化# print(dic,type(dic))# print(ret,type(ret))## res = json.loads(ret) # 反序列化# print(res,type(res))# 问题2  错把元组转成列表# dic = {1 : [1,2,3],2 : (4,5,‘aa‘)}# ret = json.dumps(dic)  # 序列化# print(dic,type(dic))# print(ret,type(ret))# res = json.loads(ret) # 反序列化# print(res,type(res))# 问题3# s = {1,2,‘aaa‘}# json.dumps(s)# 问题4 # TypeError: keys must be a string   字典key值位元组直接报错# json.dumps({(1,2,3):123})

  

多此dump和多次load的问题:不支持多次dump和load

# 问题5 不支持连续的存 取# dic = {‘key1‘ : ‘value1‘,‘key2‘ : ‘value2‘}# with open(‘json_file‘,‘a‘) as f:#     json.dump(dic,f)#     json.dump(dic,f)#     json.dump(dic,f)# with open(‘json_file‘,‘r‘) as f:#     dic = json.load(f)# print(dic.keys())

  

上面的解决办法就是使用dumps和loads,因为在内存中,一行一行的写(加上换行符),一行一行的读

# 需求 :就是想要把一个一个的字典放到文件中,再一个一个取出来???# dic = {‘key1‘ : ‘value1‘,‘key2‘ : ‘value2‘}## with open(‘json_file‘,‘a‘) as f:#     str_dic = json.dumps(dic)#     f.write(str_dic+‘\n‘)#     str_dic = json.dumps(dic)#     f.write(str_dic + ‘\n‘)#     str_dic = json.dumps(dic)#     f.write(str_dic + ‘\n‘)# with open(‘json_file‘,‘r‘) as f:#     for line in f:#         dic = json.loads(line.strip())#         print(dic.keys())

  

python-json的用法

评论关闭