吾八哥学Python(十一):JSON数据的生成与解析
JSON(JavaScript Object Notation, JS 对象标记) 是一种轻量级的数据交换格式。官方网站:http://www.json.org/
编程的过程中我们经常会遇到各种API接口的返回结果是json字符串,那么在Python里面如何去解析和生成JSON数据呢?今天就来尝试一下!
Python操作json的标准api库参考:http://docs.python.org/library/json.html
先看看具体的数据类型转换表吧,以下表格网络搜索而来!
Python与JSON数据类型互相转换对应表
1.Python 编码为 JSON 类型转换对应表:
| Python | JSON |
|---|---|
| dict | object |
| list, tuple | array |
| str | string |
| int, float, int- & float-derived Enums | number |
| True | true |
| False | false |
| None | null |
2.JSON 解码为 Python 类型转换对应表:
| JSON | Python |
|---|---|
| object | dict |
| array | list |
| string | str |
| number (int) | int |
| number (real) | float |
| true | True |
| false | False |
| null | None |
Python里实现JSON数据类型的处理
Python3里处理JSON数据的模块名就叫json,它包含了两个函数:
json.dumps(): 对数据进行编码。
json.loads(): 对数据进行解码。
1.生成JSON数据的实现
# Autor: 5bug
# WebSite: http://www.5bug.wang
# 吾八哥网技术交流QQ群: 643829693
import json
data = {}
#字符型
data['name'] = '5bug'
#整型
data['age'] = 31
#浮点型
data['mark'] = 99.99
#布尔型
data['marriage'] = True
#数组
data['like'] = ['code', 'girl', 'tour']
jsonString = json.dumps(data)
print(jsonString)执行上面的代码,输出结果如下:
{"name": "5bug", "age": 31, "mark": 99.99, "marriage": true, "like": ["code", "girl", "tour"]}2.解析JSON数据
# Autor: 5bug
# WebSite: http://www.5bug.wang
# 吾八哥网技术交流QQ群: 643829693
import json
jsonString = '{"name": "5bug", "age": 31, "mark": 99.99, "marriage": true, "like": ["code", "girl", "tour"]}'
data = json.loads(jsonString)
print(data['name'])
print(data['age'])
print(data['mark'])
print(data['marriage'])
print(data['like'])执行上面的代码结果如下:
5bug 31 99.99 True ['code', 'girl', 'tour']
这样就完成了JSON数据的生成与解析了,感觉比其他语言简单多了。
本文首发学Python网:http://www.xuepython.wang