About JSON
思考题:
- 如何获得 API 返回的数据?
r.text
- 如何在 Python 中处理 JSON 数据?
- JSON 的来历是什么? 为什么绝大多数 API 都选择以 JSON 的方式传递数据?
Introduction
FROM json.org
JSON是轻量级的数据交换格式。即适合人的读写操作,又适合机器解析及生成数据。JSON是基于JavaScript语言。JSON格不依附于任何一种编程语言,但是遵守C语言家族惯例,包括C, C++, C#, Java, Perl, Python, 及其它。因此JSON是最合适的数据交换语言。
JSON基于两个结构:
- 一系列的名称/值对。其他语言中称其为object, record, struct, dictionary, hash table, keyed list, associative arry
- 有序的值列表,其他语言中城市为array, vector, list, or sequence.
json - JSON encoder and decoder
Encoding
import json
json.dumps()
## compact encoding
son.dumps([1,2,3,{'4': 5, '6': 7}], separators=(',', ':'))
## pretty printing
print(json.dumps({'4': 5, '6': 7}, sort_keys=True, indent=4))
Decoding
json.loads()
json.load()
感觉loads 和 dumps可以解决大部分使用json的环境,暂不深入研读文档其余部分。目前的疑问是
json.dumps()
和json.dump()
的区别是什么?以及json.loads()
和json.load()
区别?
dump()
和load()
是对类文件对象进行写入/读取,而dumps()
和loads()
是对字符串进行读写。读取文件时不需要用dumps()
存储json字符串。
两个参考资料 json处理小技巧 Use dump instead of dumps for json files
不推荐的方式
dictionary = {"key": "value"}
with open("json_file.json", "w") as json_file:
json_string = json.dumps(dictionary)
json_file.write(json_string)
推荐的方式
dictionary = {"key": "value"}
with open("json_file.json", "w") as json_file:
json.dump(dictionary, json_file)
f = open("json_file.json", "r")
json_str = json.load(f)
EOF