您的位置:首页 > 编程语言 > Python开发

python中json.dumps()/loads()/dump()/load()使用

2017-08-10 00:39 986 查看
python中的json模块可以将dict转str,str转dict,dict存储到文件中,文件中导入成dict

dict={'user':'john','sex':'male'}
str=json.dumps(dcit)#<class 'str'>
print(json.loads(str))#{'user': 'john', 'sex': 'male'}


#可以直接用字符串转换
str1='{"user":"john","sex":"male"}'
print(json.loads(str1))#{'user': 'john', 'sex': 'male'}



导出和导入文件的代码

str='{"user":"john","sex":"male"}'

with open('test.txt','w',encoding='utf-8') as fout:
json.dump(str,fout)
fout.close()

with open('test.txt','r',encoding='utf-8') as fout:
print(json.load(fout))
fout.close()

json还可以将dict的list转成str存到文件里,再用load可以读入成一个dict格式的list

with open('test.txt','w',encoding='utf-8') as f:
f.writelines(json.dumps([{'hello':'world'},{'hello':'world'},{'hello':'world'}]))
print(type(json.dumps([{'hello':'world'},{'hello':'world'},{'hello':'world'}])))
f.close()

with open('test.txt','r',encoding='utf-8') as f:
test_l=json.load(f)
print(type(test_l[0]))
f.close()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: