[英]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.