一、json
概述:
json.dumps():将 Python 对象编码成 JSON 字符串, dic -> json str
json.dump() :将 Python 对象保存成 JSON 字符串格式到文件中。
json.loads() :将已编码的 JSON 字符串解码为 Python 对象, json str -> dic
json.load() :从文件中读取json数据
ps:
如果dic中的key不是string类型,编码的时候会变成string类型。所以编码之后再解码,得到的结果可能和原始数据不同。
JSON必须使用双引号来包裹字符串,而不能使用单引号。如果在字符串中出现引号可以加上转义字符\ 。
对象和数组很关键的一个区别就是,对象是 “名称--值“对 构成的列表或集合,数组是 值 构成的列表或集合;还有一点就是数组中所有的值应该具有相同的数据类型。
实例:
import json
# json.dumps() In [67]: list1 = [{'a': 1, 'a2': 2, 'a3': 3}, {'c': [111,222,333]}, {'b': 11}] In [68]: jstr1 = json.dumps(list1) In [69]: jstr2 = json.dumps(list1,sort_keys=True, indent=4) In [70]: print jstr1 [{"a": 1, "a3": 3, "a2": 2}, {"c": [111, 222, 333]}, {"b": 11}] In [71]: print jstr2 [ { "a": 1, "a2": 2, "a3": 3 }, { "c": [ 111, 222, 333 ] }, { "b": 11 } ] # json.dump() In [72]: f = open('./jstr.txt','w+') In [73]: json.dump(list1,f,indent=4) #json.dump(x,f),x是对象,f是一个文件对象,这个方法可以将json字符串写入到文本文件中。 In [74]: f.close() In [75]: cat jstr.txt [ { "a": 1, "a3": 3, "a2": 2 }, { "c": [ 111, 222, 333 ] }, { "b": 11 } ] # json.loads() In [76]: json.loads(jstr1) Out[76]: [{u'a': 1, u'a2': 2, u'a3': 3}, {u'c': [111, 222, 333]}, {u'b': 11}] # json.load() In [77]: f2 = open('./jstr.txt','r+') In [78]: result = json.load(f2) In [79]: result Out[79]: [{u'a': 1, u'a2': 2, u'a3': 3}, {u'c': [111, 222, 333]}, {u'b': 11}]
参数简介
1. json.dump
(obj, fp, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw)¶
- 将obj序列化为JSON格式的流到fp (支持类文件对象)。json模块总是生成str对象,而不是bytes对象。因此,fp.write()必须支持str输入。
- 如果skipkeys为真(默认值:False),那么将跳过不属于基本类型(str、int、float、bool、None)的dict键,而不是引发类型错误。
- 如果ensure_ascii为真(默认值),则保证输出将转义所有传入的非ascii字符。如果ensure_ascii为假,这些字符将按原样输出。
- 如果check_circular为false(默认值:True),则将跳过容器类型的循环引用检查
- 如果allow_nan为false(默认值:True),那么在严格遵循JSON规范的情况下序列化超出范围的浮点值(nan, inf, -inf)将是一个ValueError。
- 如果indent缩进是非负整数或字符串,那么JSON数组元素和对象成员将使用该缩进级别漂亮地打印。缩进级别为0、负数或""只会插入换行。None(默认值)选择最紧凑的表示。使用正整数缩进,即每层缩进多个空格。如果缩进是一个字符串(例如“\t”),该字符串用于缩进每个级别。版本不同可能有些差别。
- 要使用自定义JSONDecoder子类,请使用cls kwarg指定它;否则使用JSONDecoder。其他关键字参数将传递给类的构造函数。https://blog.csdn.net/rush_mj/article/details/79168075
- 如果sort_keys为真(默认值:False),那么字典的输出将按键排序。
2. json.dumps
(obj, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw)¶
3. json.load
(fp, *, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)
- 将fp反序列化为Python对象。
4. json.loads
(s, *, encoding=None, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)¶
类型转换
python 原始类型向 json 类型的转化对照表:
Python | JSON |
---|---|
dict | object |
list, tuple | array |
str, unicode | string |
int, long, float | number |
True | true |
False | false |
None | null |
json 类型转换到 python 的类型对照表:
JSON | Python |
---|---|
object | dict |
array | list |
string | unicode |
number (int) | int, long |
number (real) | float |
true | True |
false | False |
null | None |
二、demjson
ps:
Demjson 是 python 的第三方模块库,可用于编码和解码 JSON 数据,包含了 JSONLint 的格式化及校验功能。
Github 地址:https://github.com/dmeranda/demjson
官方地址:http://deron.meranda.us/python/demjson/
安装:pip install demjson
概述
demjson.encode()
demjson.encode_to_file()
demjson.decode()
demjson.decode_file()
实例
1. 编码成JSON格式
In [155]: import demjson In [156]: d1 = [{'1':1,'4':4,'2':2,'5':5,'3':3}] In [157]: d2 = [{'c':2,'a':5,'b':3}] In [158]: demjson.encode(d1) Out[158]: u'[{"1":1,"2":2,"3":3,"4":4,"5":5}]' In [159]: demjson.encode_to_file('f1.txt',d1) In [160]: cat f1.txt [{"1":1,"2":2,"3":3,"4":4,"5":5}] In [161]: demjson.encode_to_file('f1.txt',d2,overwrite=True) In [162]: cat f1.txt [{"a":5,"b":3,"c":2}]
2. 解码成Python对象
In [172]: jstr = '{"a":1,"d":4,"c":3,"b":2}' In [173]: demjson.decode(jstr) Out[173]: {u'a': 1, u'b': 2, u'c': 3, u'd': 4} In [174]: cat f2.txt {"a":1,"d":4,"c":3,"b":[2,3,4]} In [175]: demjson.decode_file('f2.txt') Out[175]: {u'a': 1, u'b': [2, 3, 4], u'c': 3, u'd': 4}
3. 检查JSON格式
In [209]: c = demjson.jsonlint() #jsonlint是demjson中的一个类 In [210]: cat f2.txt {"a":1,"d":4,"c":3,"b":[2,3,4]} In [211]: c.main(['f2.txt']) #如果格式正确,则返回0 f2.txt: ok #说明是正确的JSON格式 Out[211]: 0 In [212]: cat f1.txt {1:11,2:22} In [213]: c.main(['f1.txt']) f1.txt:1:1: Warning: JSON only permits string literals as object properties (keys) | At line 1, column 1, offset 1 | Object started at line 1, column 0, offset 0 (AT-START) f1.txt:1:6: Warning: JSON only permits string literals as object properties (keys) | At line 1, column 6, offset 6 | Object started at line 1, column 0, offset 0 (AT-START) f1.txt: ok, with warnings Out[213]: 1 In [214]: c.main(['--help']) #查看帮助文档,注意这里是list,并且注意参数顺序
4. 格式化输出:
In [245]: c = demjson.jsonlint() In [246]: c.main(["-f","f2.txt"]) #-f | --format Reformat the JSON text (if conforming) to stdout { "a" : 1, "b" : [ 2, 3, 4 ], "c" : 3, "d" : 4 } Out[246]: 0
In [253]: c.main(["-f","-o","obj.txt","f2.txt"]) #-o filename | --output filename The filename to which reformatted JSON is to be written.
Out[253]: 0
In [254]: cat obj.txt
{
"a" : 1,
"b" : [
2,
3,
4
],
"c" : 3,
"d" : 4
}