1)json.dumps()
将一个Python数据类型dict进行json格式的编码(字典->字符串)
eg:
age_dict = {'age1':'12', 'age2':'15'}
json_info = json.dumps(age_dict)
print("json_info = {}".format(json_info))
print("json_info type = {}".format(type(json_info)))
2)json.loads()
将json格式数据转换为dict(字符串->字典)
json_age ='{"age1": "12", "age2": "15"}'
dict_age = json.loads(json_info)
print("json_age = {}".format(json_age))
print("dict_age type = {}".format(str(type(dict_age))))
3)json.load()
读取文件,将里json格式字符串转化为dict
with open(test.json, 'r') as file:
contents = json.load(file)
print(contents)
4)json.dump()
将dict类型转换为json格式字符串,存入文件
number = [1, 2, 3, 5]
file = 'number.json'
with open(file , 'w') as file:
json.dump(number, file)
import json,time
infos = {"_id":"description","name":"python","filename":"中文","os":["abcd","hello","www"]}
infos["time"] = time.time()#动态修改json文件内容
#生成json文件
def json_file(infos):
with open("./static/desc.desc","w") as jsonf:
jsonf.write(json.dumps(infos))
json_file(infos)
#读取json文件的内容
file_info = json.load(file("./static/desc.desc"))
print file_info,type(file_info)
filename = file_info["filename"]
print filename
infos = json.dumps(file_info,sort_keys=True,indent=4)
print infos,type(infos)
python使用json模块来处理json数据
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)