一、json的特点
1、只能处理简单的可序列化的对象;(字典,列表,元祖)
2、json支持不同语言之间的数据交互;(python - go,python - java)
二、使用场景
1、玩游戏的时候存档和读取记录。
2、虚拟机挂起、保存或者恢复、读档的时候。
三、具体案例:
#!/usr/bin/env python # -*- coding:utf-8 -*- # Author:Huanglinsheng #不带s的用于操作文件,带s的用于数据类型的转换 import json test_dict = {'bigberg': [7600, {1: [['iPhone', 6300], ['Bike', 800], ['shirt', 300]]}]} print(test_dict) print(type(test_dict)) #dumps 将数据转换成字符串 #dumps:将python中的 字典 转换为 字符串 json_str = json.dumps(test_dict) print(json_str) print(type(json_str)) #loads: 将 字符串 转换为 字典 new_dict = json.loads(json_str) print(new_dict) print(type(new_dict)) #dump: 将数据写入json文件中 with open("1","w") as f: json.dump(new_dict,f) print("加载入文件完成。。。。") #load:把文件打开,并把字符串变换为数据类型 with open('1','r') as load_f: load_dict = json.load(load_f) print(load_dict) load_dict['samllberg'] = [8200,{1:[['Python',81],['shirt',300]]}] print(load_dict) with open('1','w') as dump_f: json.dump(load_dict,dump_f)
#!/usr/bin/env python # -*- coding:utf-8 -*- # Author:Huanglinsheng import json with open("1.txt",'r') as load_f: load_dict = json.load(load_f) print(load_dict) # for line in load_f: # print(json.loads(line)) version_dict = load_dict['version_info']['assets_info']['version'] update_url = load_dict['param_list']['update_url'] print(version_dict) print(update_url)
序列化:
#!/usr/bin/env python # -*- coding:utf-8 -*- # Author:Huanglinsheng import json test = r'test.txt' info = { 'name' : 'alex', 'age' : 32 } with open(test,'w',encoding='utf-8') as f: f.write( json.dumps(info) )
反序列化:
import json test = r'test.txt' with open(test,'r',encoding='utf-8') as f: data = json.loads( f.read() ) print(data) print(data['name']) print(data['age'])