python对rfc 7464 json文本序列的支持
jsonseq的Python项目详细描述
jsonseq
RFC 7464 JSON Text Sequencespython的编码和解码。
用法
jsonseq.encode.JSONSeqEncoder
类接受可序列化的json流。
python对象并为每个对象生成其json表示
在可选的ascii记录分隔符(rs,\x1e
)和换行符(\n
)之间。
>>>fromjsonseq.encodeimportJSONSeqEncoder>>>forchunkinJSONSeqEncoder().encode(({"a":i,"b":i}foriinrange(3))):...print(repr(chunk))...'{"a": 0, "b": 0}\n''{"a": 1, "b": 1}\n''{"a": 2, "b": 2}\n'
rs允许漂亮的打印json流式输出,序列可以是 再次解码。
>>>forchunkinJSONSeqEncoder(with_rs=True,indent=2).encode(({"a":i,"b":i}foriinrange(3))):...print(repr(chunk))...'\x1e{\n "a": 0,\n "b": 0\n}\n''\x1e{\n "a": 1,\n "b": 1\n}\n''\x1e{\n "a": 2,\n "b": 2\n}\n'
您还可以获得json序列的小块,因为它们是用
iterencode()
方法。
>>>forchunkinJSONSeqEncoder(with_rs=True).iterencode(({"a":i}foriinrange(3))):...print(repr(chunk))...'\x1e''{''"a"'': ''0''}''\n''\x1e''{''"a"'': ''1''}''\n''\x1e''{''"a"'': ''2''}''\n'
可以使用encode()
或iterencode()
将json文本序列复制到文件中。
withopen("/tmp/example.jsons","w")asf:forchunkinJSONSeqEncoder(with_rs=True,indent=2).iterencode(({"a":i,"b":i}foriinrange(3))):f.write(chunk)
调用文件的write()
方法时不需要添加换行符。
jsonseqencoder确保它已经在需要的地方了。
jsonseq.decode.JSONSeqDecoder
类接受json文本流
夹在可选的ascii记录分隔符(rs,\x1e
)和
换行符(\n
)并产生解码的python对象。
>>>stream=['\x1e','{','"a"',': ','0','}','\n','\x1e','{','"a"',': ','1','}','\n','\x1e','{','"a"',': ','2','}','\n']>>>forobjinJSONSeqDecoder().decode(stream):...print(repr(obj))...{'a':0}{'a':1}{'a':2}
可以用同样的方法从文件中读取对象。
>>>withopen("/tmp/example.jsons")asf:...forobjinJSONSeqDecoder().decode(f):...print(repr(obj))...{'a':0,'b':0}{'a':1,'b':1}{'a':2,'b':2}