python_python学习_Json

资料

https://docs.python.org/3/library/json.html

http://json.org/

http://www.cnblogs.com/coser/archive/2011/12/14/2287739.html

http://www.jb51.net/article/73450.htm


一、Encoders and Decoders

1-1 解码时的类型对应关系

class  json. JSONDecoder ( *object_hook=Noneparse_float=Noneparse_int=Noneparse_constant=Nonestrict=Trueobject_pairs_hook=None )

JSON Python
object dict
array list
string str
number (int) int
number (real) float
true True
false False
null None

#========解码
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]


1-2 编码时的类型对应关系

class  json. JSONEncoder ( *skipkeys=Falseensure_ascii=Truecheck_circular=Trueallow_nan=Truesort_keys=Falseindent=Noneseparators=Nonedefault=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
# }




你可能感兴趣的:([7]python,python)