0

我正在尝试在 Python 中使用 simplejson 解析谷歌翻译结果。但我收到以下异常。

Traceback (most recent call last):
  File "Translator.py", line 45, in <module>
    main()
  File "Translator.py", line 41, in main
    parse_json(trans_text)
  File "Translator.py", line 29, in parse_json
    json = simplejson.loads(str(trans_text))
  File "/usr/local/lib/python2.6/dist-packages/simplejson-2.1.3-py2.6-linux-i686.egg/simplejson/__init__.py", line 385, in loads
    return _default_decoder.decode(s)
  File "/usr/local/lib/python2.6/dist-packages/simplejson-2.1.3-py2.6-linux-i686.egg/simplejson/decoder.py", line 402, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/local/lib/python2.6/dist-packages/simplejson-2.1.3-py2.6-linux-i686.egg/simplejson/decoder.py", line 418, in raw_decode
    obj, end = self.scan_once(s, idx)
simplejson.decoder.JSONDecodeError: Expecting property name: line 1 column 1 (char 1)

这是我的 json 对象看起来像

{'translations': [{'translatedText': 'fleur'}, {'translatedText': 'voiture'}]}

谁能告诉我这里有什么问题?

4

3 回答 3

4

问题是 simplejson 支持带有双引号编码字符串而不是单引号编码字符串的 json,所以一个天真的解决方案可能是

json.loads(jsonstring.replace("'", '"'))
于 2011-04-12T07:02:53.277 回答
4

你在做simplejson.loads(str(trans_text))

trans_text不是字符串( str或 unicode)或缓冲区对象。simplejson错误消息和您的报告证明了这一点repr(trans_text)

这是我的反文本代表 {'translations': [{'translatedText': 'hola'}]}

trans_text是一本字典

如果要将其转换为 JSON 字符串,则需要使用simplejson.dumps(),而不是simplejson.loads().

如果您想将结果用于其他用途,您只需要挖掘数据,例如

# Your other example
trans_text = {'translations': [{'translatedText': 'fleur'}, {'translatedText': 'voiture'}]} 
for x in trans_text['translations']:
    print "chunk of translated text:", x['translatedText']
于 2011-04-14T07:14:45.413 回答
2

JSON 语法不支持 JavaScript 的完整语法。与 JavaScript 不同,JSON 字符串和属性名称必须用双引号引起来。

字符串::= ""| " 字符 "

于 2011-04-12T07:07:49.460 回答