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

本文介绍Python中JSON模块的基本使用方法,包括如何将字典转换为字符串、字符串转换为字典,以及如何将字典存储到文件中并从文件中读取。通过示例展示了基本操作流程,并介绍了如何处理包含列表的数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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()



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值