Python3 JSON 数据解析
JSON (JavaScript Object Notation) 是一种轻量级的数据交换格式。它基于ECMAScript的一个子集。
Python3 中可以使用 json 模块来对 JSON 数据进行编解码,它包含了两个函数:
- json.dumps(): 对数据进行编码。
- json.loads(): 对数据进行解码。
在json的编解码过程中,python 的原始类型与json类型会相互转换,具体的转化对照如下:
Python 编码为 JSON 类型转换对应表:
| Python | JSON |
|---|---|
| dict | object |
| list, tuple | array |
| str | string |
| int, float, int- & float-derived Enums | number |
| True | true |
| False | false |
| None | null |
JSON 解码为 Python 类型转换对应表:
| JSON | Python |
|---|---|
| object | dict |
| array | list |
| string | str |
| number (int) | int |
| number (real) | float |
| true | True |
| false | False |
| null | None |
json.dumps 与 json.loads 实例
以下实例演示了 Python 数据结构转换为JSON:
实例(Python 3.0+)
执行以上代码输出结果为:
Python 原始数据: {'url': 'http://www.codercto.com', 'no': 1, 'name': 'Codercto'}
JSON 对象: {"url": "http://www.codercto.com", "no": 1, "name": "Codercto"}
通过输出的结果可以看出,简单类型通过编码后跟其原始的repr()输出结果非常相似。
接着以上实例,我们可以将一个JSON编码的字符串转换回一个Python数据结构:
实例(Python 3.0+)
执行以上代码输出结果为:
Python 原始数据: {'name': 'Codercto', 'no': 1, 'url': 'http://www.codercto.com'}
JSON 对象: {"name": "Codercto", "no": 1, "url": "http://www.codercto.com"}
data2['name']: Codercto
data2['url']: http://www.codercto.com
如果你要处理的是文件而不是字符串,你可以使用 json.dump() 和 json.load() 来编码和解码JSON数据。例如:
实例(Python 3.0+)
更多资料请参考:https://docs.python.org/3/library/json.html
点击查看所有 Python 3 教程 文章: https://codercto.com/courses/l/10.html
The Art and Science of Java
Eric Roberts / Addison-Wesley / 2007-3-1 / USD 121.60
In The Art and Science of Java, Stanford professor and well-known leader in CS Education Eric Roberts emphasizes the student-friendly exposition that led to the success of The Art and Science of C. By......一起来看看 《The Art and Science of Java》 这本书的介绍吧!