作者uranusjr (←这人是超级笨蛋)
看板Python
标题Re: [问题] 如何读取大量json档
时间Thu Dec 7 22:21:40 2017
※ 引述《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() 允许结尾有多余资料, 但开头就不行
还是得把多的空白与换行清掉
--
╱ ̄ ̄ ̄╲
▏
◢█◣ ▏
︻█︻█ ▏
成龙表示: 是喔...
′/ ‵ ▏
╰╯ █╱
ψQSWEET ◥︶█◤
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 218.161.19.12
※ 文章网址: https://webptt.com/cn.aspx?n=bbs/Python/M.1512656502.A.25A.html
1F:推 a11780922: 真的非常谢谢! 12/08 13:37