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