簡體   English   中英

從 python 中的文本文件中讀取 JSON 數組

[英]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文件。

您最后有兩個選項可以修復它:

  • 將所有 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM