![journalctl json 输出破坏了 python 的 json 解析器](https://linux22.com/image/1168370/journalctl%20json%20%E8%BE%93%E5%87%BA%E7%A0%B4%E5%9D%8F%E4%BA%86%20python%20%E7%9A%84%20json%20%E8%A7%A3%E6%9E%90%E5%99%A8.png)
Ubuntu 19.04 Python 3.7
创建一个 json 文件:
journalctl -ojson -r > a.json
现在读一下:
with open('a.json') as infile :
data = json.load(infile)
Traceback (most recent call last):
File "journalctl.json.py", line 4, in <module>
data = json.load(infile)
File "/usr/lib/python3.7/json/__init__.py", line 296, in load
parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)
File "/usr/lib/python3.7/json/__init__.py", line 348, in loads
return _default_decoder.decode(s)
File "/usr/lib/python3.7/json/decoder.py", line 340, in decode
raise JSONDecodeError("Extra data", s, end)
json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 985)
这是第 2 行
{"_HOSTNAME":"vaio","_CAP_EFFECTIVE":"3fffffffff","_SELINUX_CONTEXT":"unconfined\n","_COMM":"anacron","_SYSTEMD_UNIT":"anacron.service","MESSAGE":"Normal exit (0 jobs run)","_SOURCE_REALTIME_TIMESTAMP":"1570415470605362","SYSLOG_FACILITY":"9","_BOOT_ID":"06344b4eb91344bf8c1ce7c49f77ee5d","_UID":"0","PRIORITY":"5","__CURSOR":"s=2b70948bafe3422ca5fa14213e18cda1;i=3c78c;b=06344b4eb91344bf8c1ce7c49f77ee5d;m=83ae2587;t=59448d8467447;x=24f85cc398f54cab","_PID":"22196","SYSLOG_IDENTIFIER":"anacron","_SYSTEMD_INVOCATION_ID":"3cc36dc0214b4f98a311fc110648019e","__MONOTONIC_TIMESTAMP":"2209228167","_CMDLINE":"/usr/sbin/anacron -d -q -s","_SYSTEMD_CGROUP":"/system.slice/anacron.service","_MACHINE_ID":"dc7bf55ee6014b7db63fba929237b2c9","_TRANSPORT":"syslog","_GID":"0","SYSLOG_TIMESTAMP":"Oct 6 19:31:10 ","__REALTIME_TIMESTAMP":"1570415470605383","_EXE":"/usr/sbin/anacron","SYSLOG_PID":"22196","_SYSTEMD_SLICE":"system.slice"}
答案1
您收到错误。json.decoder.JSONDecodeError: Extra data error
原因是 load 方法只能处理单个 JSON 对象。而您的文件似乎包含多个 JSON 对象。使用以下代码解析包含多个对象的 JSON 文件
jsonData = []
with open('a.json') as f:
jsonData = [json.loads(line) for line in f]
print(jsonData)
答案2
import json
lines = []
with open('C:\\Users\\Owner\\Desktop\\jsondata.txt','r') as file:
for line in file:
lines.append(json.loads(line))
print(lines)