0

I am currently trying to create a dictionary from a json formatted server response:

{"id": null,{"version": "1.1","result": "9QtirjtH9b","error": null}}

Therefore I am using json.loads(). But I always get the following error:

ValueError: Expecting property name: line 1 column 12 (char 12)

I know that this means that there is an error in the json syntax and I found some threads (like this one) here at stackoverflow, but they did not include an answer that solved my problem.

However, I was not sure if the null value within the json response causes the error, so I had a closer look at the json.org Reference Manual and it seems to be a valid syntax. Any ideas?

4

2 回答 2

2

这是无效的。外部对象需要第二个元素的属性名称;原始值在对象中无效。

{"id": null, "somename":{"version": "1.1","result": "9QtirjtH9b","error": null}}
于 2013-07-03T08:53:41.063 回答
0

这里的问题是缺少嵌套对象的键,而不是null. 您需要找到一种方法来修复该语法或自己解析它。

如果我们对语法做一些假设,您应该能够在解码之前使用正则表达式来修复 JSON 数据:

import re
from itertools import count

def _gen_id(match, count=count()):
    return '{1}"generated_id_{0}":{2}'.format(next(count), *match.groups())

_no_key = re.compile(r'(,)({)')

def fix_json(json_data):
    return _no_key.sub(_gen_id, json_data)

这假定任何,{组合都指示丢失键的位置,并生成一个以插入那里。这是一个合理的假设,但如果您的字符串数据恰好具有该序列,则可能会破坏事情。

演示:

>>> json_data = '{"id": null,{"version": "1.1","result": "9QtirjtH9b","error": null}}'
>>> fix_json(json_data)
'{"id": null,"generated_id_0":{"version": "1.1","result": "9QtirjtH9b","error": null}}'
>>> json.loads(fix_json(json_data))
{u'id': None, u'generated_id_1': {u'version': u'1.1', u'result': u'9QtirjtH9b', u'error': None}}
于 2013-07-03T09:10:03.097 回答