在本教程中, 您将学习如何借助示例在 Python 中解析, 读取和编写 JSON. 此外, 您将学习将 JSON 转换为 dict 并将其打印出来.
JSON 简介
JSON (JavaScript Object Notation) 是一种用于表示结构化数据的流行数据格式. 常用于服务器和 web 应用程序之间传输和接收数据.
在 Python 中, JSON 以字符串形式表示. 例如:
p = '{"name":"Bob","languages": ["Python","Java"]}'
将 JSON 对象存储在文件中也很常见.
J 在 Python 中解析 JSON
使用 JSON 模块可以轻松解析包含 JSON 对象的 JSON 字符串和文件.
- import JSON
- person = '{"name":"http://china-testing.github.io/","languages": ["English","Fench"]}'
- person_dict = JSON.loads(person)
- # Output: {
- 'name': 'http://china-testing.github.io/', 'languages': ['English', 'Fench']
- }
- print( person_dict)
- # Output: ['English', 'French']
- print(person_dict['languages'])
执行结果
$ python3 test.py { 'name': 'http://china-testing.github.io/', 'languages': ['English', 'Fench'] } ['English', 'Fench']
这里, person 是 JSON 字符串, person_dict 是字典
您可以使用 JSON.load() 方法读取包含 JSON 对象的文件.
假设您有名为 person.JSON 的文件, 其中包含 JSON 对象
import JSON with open('person.json') as f: data = JSON.load(f) # Output: {'languages': ['English', 'Fench'], 'name': 'http://china-testing.github.io/'} print(data)
我们使用 open() 函数来读取 JSON 文件. 然后, 使用 JSON.load() 方法解析文件, 该方法为我们提供了名为 data 的字典.
以使用 JSON.dumps() 方法将字典转换为 JSON 字符串.
import JSON person_dict = { 'name': 'Bob', 'age': 12, 'children': None } person_json = JSON.dumps(person_dict) # Output: { "name": "Bob", "age": 12, "children": null } print(person_json)
JSON.dump() 方法将 JSON 写入文件.
import JSON person_dict = {"name": "Bob", "languages": ["English", "Fench"], "married": True, "age": 32 } with open('person.txt', 'w') as json_file: JSON.dump(person_dict, json_file)
参考资料
python 测试开发项目实战 - 目录 https://china-testing.github.io/practices.html
python 工具书籍下载 - 持续更新 https://china-testing.github.io/python_books.html
python 3.7 极速入门教程 - 目录 https://china-testing.github.io/python3_quick.html
讨论 qq 群 630011153 144081101
import JSON person_string = '{"name":"Bob","languages":"English","numbers": [2, 1.6, null]}' # Getting dictionary person_dict = JSON.loads(person_string) # Pretty Printing JSON string back print(JSON.dumps(person_dict, indent = 4, sort_keys=True))
{ "languages": "English", "name": "Bob", "numbers": [ 2, 1.6, null ] }
来源: http://www.jianshu.com/p/13c9de8e9267