Python解析json字符串,json字符串用法
json数据简介
json数据是一个轻量级的数据交换格式,采用完全独立于语言的文本格式,这些特性使json称为理想的数据交换语言,易于人阅读和编写,同时易于机器解析和生成。
json中的字符集必须是UTF-8,json中的字符串必须用双引号引起来。几乎所有语言都内置了解析json的库,JavaScript语言可以直接使用json。
json格式一般是“键值对”的格式,比如
键值对:{“firstName”:”Breet”,”lastName”:”MMM”,”email”:”XXX”}
再比如:
{
“programers”:[
{“firstName”:”Breet”,”lastName”:”MMM”,”email”:”XXX”},
{“firstName”:”Breet”,”lastName”:”MMM”,”email”:”XXX”}
],
“authors”:[
{“firstName”:”Breet”,”lastName”:”MMM”,”email”:”XXX”},
{“firstName”:”Breet”,”lastName”:”MMM”,”email”:”XXX”}
],
}
json的应用场景:web服务端的go数组->json字符串->网络传输->json字符串->反序列化->go数组->信息呈现给用户。
Python中解析json的库
import json # 字典类型转换为json字符串 data = {"id": 1, 'name': 'sy', 'passwrd': '123123'} print(type(data)) json_str = json.dumps(data) print(type(json_str)) print(json_str) print("*" * 20) # json字符串转换为字典类型 json_str2 = '{"programers":[ {"firstName":"Breet","lastName":"MMM","email":"XXX"},'\ '{"firstName":"Breet","lastName":"MMM","email":"XXX"}], ' \ '"author": [{"firstName": "su", "lastName": "yang", "email": "XXX"},'\ '{"firstName": "Breet", "lastName": "MMM", "email": "XXX"}]}' print(type(json_str2)) data2 = json.loads(json_str2) print(type(data2)) print(json_str2) print(data2) print('*' * 20) # 将json数据写入文件,用文件传送 with open('aaa.json', 'w') as f: json.dump(data, f) with open('aaa.json', 'r') as f: data3 = json.load(f) print(type(data3)) print(data3)
运行结果:
<class 'dict'>
<class 'str'>
{"id": 1, "name": "sy", "passwrd": "123123"}
********************
<class 'str'>
<class 'dict'>
{"programers":[ {"firstName":"Breet","lastName":"MMM","email":"XXX"},{"firstName":"Breet","lastName":"MMM","email":"XXX"}], "author": [{"firstName": "su", "lastName": "yang", "email": "XXX"},{"firstName": "Breet", "lastName": "MMM", "email": "XXX"}]}
{'programers': [{'email': 'XXX', 'lastName': 'MMM', 'firstName': 'Breet'}, {'email': 'XXX', 'lastName': 'MMM', 'firstName': 'Breet'}], 'author': [{'email': 'XXX', 'lastName': 'yang', 'firstName': 'su'}, {'email': 'XXX', 'lastName': 'MMM', 'firstName': 'Breet'}]}
********************
<class 'dict'>
{'id': 1, 'name': 'sy', 'passwrd': '123123'}