我使用json.dumps将一些数据写入文件。我现在正试图使用json.load和json.loads在另一个工具中读取此数据并收到此错误:
Traceback (most recent call last):
File "./compute_avg_cpu_util.py", line 16, in <module>
data = json.loads(line.rstrip())
File "/usr/local/python-2.76/lib/python2.7/json/__init__.py", line 338, in loads
return _default_decoder.decode(s)
File "/usr/local/python-2.76/lib/python2.7/json/decoder.py", line 365, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/local/python-2.76/lib/python2.7/json/decoder.py", line 383, in raw_decode
raise ValueError("No JSON object could be decoded")
ValueError: No JSON object could be decoded
以下是两行示例数据:
tail -2 file.dat | cat -vet
{"sample": 309896986, "data": {"value": 2}, "samples": 319049477, "startTime": "20151213T00:01:47"}
{"sample": 309896987, "data": {"value": 2}, "samples": 319049477, "startTime": "20151213T00:01:48"}
这是我的代码(现在):
for file in files.split(","):
with open(file, "r") as f:
data = None
for line in f:
if not line.startswith("{"):
continue
data = json.loads(line)
我可能通过这样做错误地写了这些数据文件(这些数据来自对存储设备的REST api调用):
for sample in result.getdata()['data']:
sys.stdout.write("%s\n" % json.dumps(sample))
答案 0 :(得分:2)
1)尝试捕捉任何异常:
try:
data = json.loads(line.rstrip())
except ValueError as ve:
print "ERROR: {0} cannot be parsed, exception message:{1}".format(line, ve)
continue
2) 我还测试了你的json样本,它有效:
Python 2.7.10 (default, Oct 23 2015, 18:05:06)
[GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.0.59.5)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import json
>>> json.loads('{"sample": 309896986, "data": {"value": 2}, "samples": 319049477, "startTime": "20151213T00:01:47"}')
{u'sample': 309896986, u'data': {u'value': 2}, u'startTime': u'20151213T00:01:47', u'samples': 319049477}
我将示例json行保存到sample.csv
并通过以下代码正确解析:
导入json
with open("sample.csv") as f:
for line in f:
data = json.loads(line.rstrip())
print(data)
我的猜测是它的文件中可能有一些未格式化的行。你需要调试你的行。