[英]Read JSON array from a text file in python
我正在嘗試讀取其中包含 JSON 數組的文本文件。 有人可以幫我找出我的錯誤嗎?
["io", {"in": 8, "out": 0, "dev": "68", "time": 1532035082.614868}]
["io", {"in": 0, "out": 0, "dev": "68", "time": 1532035082.97122}]
["test", {"A": [{"para1":[], "para2": true, "para3": 68, "name":"", "observation":[[2,3],[3,2]],"time": 1532035082.97122}]}]
我沒有設法讓它運行
import gzip
with gzip.open('myfile', 'rb') as f
json_data = jsonload(f)
print(json_data)
I have an error: json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 278)
I can see that my file is not a JSON file but represents a JSON array I manage to have it work with pandas but I'd想知道如何在沒有 pandas 的情況下做到這一點。
import pandas as pd
data = pd.read_json('myfile', lines=True)
print(data.head())
data = [json.loads(e) for e in f if e.strip()]
文本文件中的數據不是有效的 JSON。 這實際上是一個接一個的三個JSON文件。
您最后有兩個選項可以修復它:
我找到了 2 個選項:
選項1:pandas
pd.read_json(filepath,compression='infer', orient='records, lines=True)
選項2:逐行閱讀
with gzip.open('myfile', 'rb') as f:
lines=f.readlines()
data = [json.loads(l) for l in lines]
print(data)
選項 1 最快:
選項 1 = 0.31 秒
選項 2 = 0.42 秒
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.