json --- JSON 編碼器與解碼器¶
JSON (JavaScript Object Notation) 是一個輕量化的資料交換格式,在 RFC 7159(其廢棄了 RFC 4627)及 ECMA-404 裡面有詳細說明,它啟發自 JavaScript 的物件字面語法 (object literal syntax)(雖然它並不是 JavaScript 的嚴格子集 [1])。
備註
The term "object" in the context of JSON processing in Python can be ambiguous. All values in Python are objects. In JSON, an object refers to any data wrapped in curly braces, similar to a Python dictionary.
警告
當剖析無法信任來源的 JSON 資料時要小心。一段惡意的 JSON 字串可能會導致解碼器耗費大量 CPU 與記憶體資源。建議限制剖析資料的大小。
此模組為習慣標準函式庫 marshal 與 pickle 模組的使用者提供熟悉的 API。
對基本 Python 物件階層進行編碼:
>>> import json
>>> json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}])
'["foo", {"bar": ["baz", null, 1.0, 2]}]'
>>> print(json.dumps("\"foo\bar"))
"\"foo\bar"
>>> print(json.dumps('\u1234'))
"\u1234"
>>> print(json.dumps('\\'))
"\\"
>>> print(json.dumps({"c": 0, "b": 0, "a": 0}, sort_keys=True))
{"a": 0, "b": 0, "c": 0}
>>> from io import StringIO
>>> io = StringIO()
>>> json.dump(['streaming API'], io)
>>> io.getvalue()
'["streaming API"]'
改用緊湊型編碼方式:
>>> import json
>>> json.dumps([1