资料
https://docs.python.org/3/library/json.html
http://www.cnblogs.com/coser/archive/2011/12/14/2287739.html
http://www.jb51.net/article/73450.htm
一、Encoders and Decoders
1-1 解码时的类型对应关系
-
class
-
#========解码 ld = json.loads('["foo", {"bar":["baz", null, 1.0, 2]}]') print(ld) #['foo', {'bar': ['baz', None, 1.0, 2]}] print(ld[1]["bar"]) #['baz', None, 1.0, 2]
json.
JSONDecoder
(
*,
object_hook=None,
parse_float=None,
parse_int=None,
parse_constant=None,
strict=True,
object_pairs_hook=None
)
JSON | Python |
---|---|
object | dict |
array | list |
string | str |
number (int) | int |
number (real) | float |
true | True |
false | False |
null | None |
1-2 编码时的类型对应关系
classjson.
JSONEncoder
(
*,
skipkeys=False,
ensure_ascii=True,
check_circular=True,
allow_nan=True,
sort_keys=False,
indent=None,
separators=None,
default=None
)
Extensible JSON encoder for Python data structures.
Supports the following objects and types by default:
Python | JSON |
---|---|
dict | object |
list, tuple | array |
str | string |
int, float, int- & float-derived Enums | number |
True | true |
False | false |
None | null |
(1)编码
#========编码 import json encodedjson = json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}]) print(encodedjson) ##["foo", {"bar": ["baz", null, 1.0, 2]}]
(2)排序
#===排序 print(json.dumps({"c": 0, "b": 0, "a": 0}, sort_keys=True)) # {"a": 0, "b": 0, "c": 0}
(3)压缩
dp1 = json.dumps([1,2,3,{'4': 5, '6': 7}], separators=(',', ':')) dp2 = json.dumps([1,2,3,{'4': 5, '6': 7}]) print("compacted: " , len(dp1)) print("uncompacted : " ,len(dp2)) # compacted: 21 # uncompacted : 27
(4)缩紧显示pretty printing,但是会添加冗余的格式站位符
print(json.dumps({'4': 5, '6': 7}, sort_keys=True, indent=4)) # { # "4": 5, # "6": 7 # }