【问题标题】:Not able to parse json in python , but able to view the text in json viewer无法在 python 中解析 json,但能够在 json viewer 中查看文本
【发布时间】:2012-12-02 02:49:02
【问题描述】:

我正在尝试在 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

【问题讨论】:

  • 因为这个网站不是很聪明...它使用eval而不是JSON.parse加载JSON。如果您无法修复输入,请尝试使用 YAML 解析器

标签: python json parsing


【解决方案1】:

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

"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}}

【讨论】:

  • 谢谢。是的,发现两次出现了额外的逗号。
猜你喜欢
  • 2013-08-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-31
  • 1970-01-01
  • 1970-01-01
  • 2020-11-04
  • 2019-11-11
相关资源
最近更新 更多