无法在python中解析json,但能够在json查看器中查看文本

时间:2012-12-02 02:49:03

标签: python json parsing

我试图在python中解析以下json文本但是我收到错误, 虽然我能够使用Json Viewer解析这个json文本。所以我想我的json文本是正确的,有人可以帮我解决这里有什么问题吗?

import json as j

data = '{"c":[{"xy":{"xstart":0,"xend":5,"ystart":1,"yend":5},"names":["D","T","O","H","L","C",],"co":["rgb(0,0,128)"]}],"Values":{"D":["11/30/2012"],"T":["09:44:00"],"O":["5848.40"],"H":["5848.40"],"L":["5847.45"],"C":["5848.40"]}}'
json_data = j.loads(data)
#print json_data["c"][0]



Traceback (most recent call last):
  File "C:json\jsonexample.py", line 4, in <module>
    json_data = j.loads(data)
  File "C:\Python27\lib\json\__init__.py", line 326, in loads
    return _default_decoder.decode(s)
  File "C:\Python27\lib\json\decoder.py", line 366, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "C:\Python27\lib\json\decoder.py", line 384, in raw_decode
    raise ValueError("No JSON object could be decoded")
ValueError: No JSON object could be decoded

1 个答案:

答案 0 :(得分:4)

看起来你的实际字符串有问题。这一行:

"names":["D","T","O","H","L","C",]

"C"之后有一个额外的逗号。尝试删除它,看看它是否按预期工作。

In [1]: import json as j

In [2]: data = '{"c":[{"xy":{"xstart":0,"xend":5,"ystart":1,"yend":5},"names":["D","T","O","H","L","C"],"co":["rgb(0,0,128)"]}],"Values":{"D":["11/30/2012"],"T":["09:44:00"],"O":["5848.40"],"H":["5848.40"],"L":["5847.45"],"C":["5848.40"]}}'

In [3]: json_data = j.loads(data)

In [4]: json_data['c'][0]
Out[4]:
{u'co': [u'rgb(0,0,128)'],
 u'names': [u'D', u'T', u'O', u'H', u'L', u'C'],
 u'xy': {u'xend': 5, u'xstart': 0, u'yend': 5, u'ystart': 1}}