json文本序列的编解码器
simplejsonseq的Python项目详细描述
simplejsonseq是RFC 7464json的简单编码器和解码器 带有api的文本序列与json和simplejson的文本序列相似。一个 json文本序列是文本文件中json项的集合,其中 每个项目前面都有一个ascii记录分隔符(^^,u+1e),通常 后跟换行符(^j,u+0a)。
要将文件转换为iterable或将iterable写入文件, 使用dump()和load()函数,类似于json模块:
>>> import io, simplejsonseq # In Python < 3, use cStringIO not io >>> s = io.StringIO() >>> simplejsonseq.dump(['hello', 'world'], s, buffered=False) >>> s.getvalue() '\x1e"hello"\n\x1e"world"\n' >>> for e in simplejsonseq.load(io.StringIO('\x1e"hello"\n\x1e"world"\n')): ... print(e) ... hello world
buffered=False设置在 它是在dump()结束时写入的,而不是只执行一次。
默认情况下,读取器接受不可分解的项并将它们包装成 InvalidJSON对象,但编写器拒绝编写这些对象。使用 strict参数可以是load和dump或JSONSeqReader 以及JSONSeqWriter来调整此行为,但请记住 RFC建议从无效输入项中恢复:
>>> import sys; sys.stderr = sys.stdout # placate doctest >>> import io, simplejsonseq # In Python < 3, use cStringIO not io >>> value = '\x1e{"parrot":\n' >>> items = list(simplejsonseq.load(value)) # doctest: +ELLIPSIS /...: InvalidJSONWarning: Read invalid JSON: '{"parrot":\n' ... >>> items [InvalidJSON('{"parrot":\n', JSONDecodeError('Expecting value: line 2 column 1 (char 11)'))] >>> list(simplejsonseq.load(value, strict=True)) Traceback (most recent call last): ... json.decoder.JSONDecodeError: Expecting value: line 2 column 1 (char 11) >>> s = io.StringIO() >>> simplejsonseq.dump(items, s) Traceback (most recent call last): ... TypeError: Object of type InvalidJSON is not JSON serializable >>> s = io.StringIO() >>> simplejsonseq.dump(items, s, strict=False) # doctest:+ELLIPSIS /...: InvalidJSONWarning: Wrote invalid JSON: '{"parrot":\n' ... >>> s.getvalue() == value True
对于更复杂的处理,请使用JSONSeqReader和 JSONSeqWriter。它们也可以作为上下文管理器来关闭 如果需要,基础文件:
>>> from simplejsonseq import JSONSeqReader, JSONSeqWriter >>> test = ['hello', 'world'] >>> with JSONSeqWriter(open("/tmp/test.jsonseq", 'w'), ... buffered=False) as w: ... w.write(test[0]) ... w.write(test[1]) ... >>> with JSONSeqReader(open("/tmp/test.jsonseq", 'r')) as r: ... print(list(r) == test) ... True
除了将buffered=False传递给 JSONSeqWriter,也可以刷新未写入的数据 显式使用flush()方法,或将flush=True传递给 单独的write()调用以在调用结束时刷新所有数据。 使用构造为 buffered=False,当然,因为它在每次输入之后都会刷新。
函数和类构造函数都传递所有额外的关键字 基础JSONDecoder或JSONEncoder的参数。这个 例如,可以用于将条目转储为可读性更强的 仍然有效!)格式:
>>> import io, simplejsonseq # In Python < 3, use cStringIO not io >>> value = [True, {'holy': 'grenade', 'killer': 'bunny'}] >>> s = io.StringIO() >>> simplejsonseq.dump(value, s, indent=2) >>> print(s.getvalue().replace('\x1e', '!'), end='') !true !{ "holy": "grenade", "killer": "bunny" } >>> list(simplejsonseq.load(s.getvalue())) == value True
文档字符串中提供了详细的文档。