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']}

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


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

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


输出:

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



案例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']}


案例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文件

我有点补充:

你可能感兴趣的:(python,python,json,开发语言)