Re: [问题] 如何读取大量json档

楼主: uranusjr (←這人是超級笨蛋)   2017-12-07 22:21:40
※ 引述《a11780922 (萝卜特务)》之铭言:
: 我的档案里面有很多json 像是这样 :
: [太长了, 略]
: 好几个独立的json
: 但是我要load时 就会错误 说有太多json
: 请问我要怎么这样读取json呢
: 我的目的是要先把里面的/r/n换掉 再转成CSV档
: 还请多多指教 谢谢
如果你不想用一些 hack 预处理资料
可以试试看 json 模组里比较底层的工具
https://docs.python.org/3/library/json.html#json.JSONDecoder.raw_decode
Decode a JSON document from s (a str beginning with a JSON document) and
return a 2-tuple of the Python representation and the index in s where
the document ended.
This can be used to decode a JSON document from a string that may have
extraneous data at the end.
范例:
import json
data = '{"foo": 1} {"bar": 2} [null, "da", "ta"]'
decoder = json.JSONDecoder() # JSON 解码器, json.loads 的底层.
objects = []
while data:
o, i = decoder.raw_decode(data) # 解码一个 top-level object.
objects.append(o)
data = data[i:].lstrip() # 继续解码剩下的资料, 直到结束.
注意每次处理资料时需要 lstrip()
虽然 raw_decode() 允许结尾有多余资料, 但开头就不行
还是得把多的空白与换行清掉
作者: a11780922 (萝卜特务)   2017-12-08 13:37:00
真的非常谢谢!

Links booklink

Contact Us: admin [ a t ] ucptt.com