Python使用JSON

案例1 dumps
将python中的字典数据编码为 JSON字符串 字符串

 import json

 test_dict = {'one':1, 'two':{2.1:['a', 'b']}
 print(test_dict)
 print(type(test_dict))
 #dumps 将数据转换成字符串
 json_str = json.dumps(test_dict)
 print(json_str)
 print(type(json_str))



输出:

{'one':1, 'two':{2.1:['a', 'b']}
<class 'dict'>
{"one":1, "two":{2.1:["a", "b"]}
<class 'str'>

案例2 loads
用于解析JSON数据,返回python中的的字典数据类型

 new_dict = json.loads(json_str)
 print(new_dict)
 print(type(new_dict))


输出:

{'one':1, 'two':{2.1:['a', 'b']}
<class 'dict'>


案例3 dump
:将python dict数据写入json文件中

 with open("../config/record.json","w") as f:
     json.dump(new_dict,f)
     print("加载入文件完成...")

json文件内容:

 {"one":1, "two":{2.1:["a", "b"]}

案例4 load
把文件打开,并把JSON字符串变换为python dict数据类型

 with open("../config/record.json",'r') as load_f:
     load_dict = json.load(load_f)
     print(load_dict)
  	  print(type(load_dict))

输出:

{'one':1, 'two':{2.1:['a', 'b']}
<class 'dict'>

案例5 格式化写入json文件
两种方法均可以实现:
1、将python字典数据用dumps()方法编码成JSON字符串,然后再写入json文件中

with open("../config/format_json.json", 'w') as write_f:
	write_f.write(json.dumps(load_dict, indent=4, ensure_ascii=False))


2.直接用dump()方法将python字典数据写入json文件中

with open("../config/format_json.json", 'w') as write_f:
	json.dump(load_dict, write_f, indent=4, ensure_ascii=False)


格式化写入json后,文件内容:

{
	'one': 1,
	'two': {
		2.1: [
			'a',
			'b'
		]
	}				
}





注意:如果要写入中文,则需要加两个东西
eg:
name_url={"1":["MV","美女"]}

with open("测试.json","w+",encoding="utf-8") as f:
    f.write(json.dumps(name_url,indent=4,ensure_ascii=False))

1 encoding="utf-8"
2 ensure_ascii=Fasle

以上大部分来自这位大佬的文章(3条消息) python读写json、格式化写入json文件_尤达c的博客-CSDN博客_python 写入json文件

我有点补充:

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

桂亭亭

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值