Python JSON谷歌翻译解析与Simplejson问题
我试图用Python中的simplejson解析Google翻译结果。但我得到了以下例外Python JSON谷歌翻译解析与Simplejson问题,python,simplejson,Python,Simplejson,我试图用Python中的simplejson解析Google翻译结果。但我得到了以下例外 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 pars
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)
有人能告诉我这里的问题是什么吗?问题是simplejson支持双引号编码的字符串而不是单引号编码的字符串,因此一个简单的解决方案可能是
json.loads(jsonstring.replace("'", '"'))
JSON语法不支持JavaScript的完整语法。与JavaScript不同,JSON字符串和属性名称必须双引号 字符串::=
”
|“
字符”
您正在执行
simplejson.load(str(trans_text))
trans_text
不是字符串(str或unicode)或缓冲区对象。这可以通过simplejson
错误消息和您的repr(trans_text)
报告来证明:
这是我的翻译报告
{'translations':[{'translatedText':
“你好”}]}
trans\u 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']
没有所谓的“json对象”。你从一个字符串开始。向我们显示
repr(trans\u text)
的结果。Google Translate API文档说的trans_text
是:str
<代码>unicode?还有别的吗?为什么您认为您需要执行str(trans_text)
?当我尝试使用simplejson进行解析时,它抛出一个错误,表示它应该是字符串或流。我不知道为什么不把这个对象当作字符串。因此,我需要String()。这是我的反文本{Retrase:ReTrimeDetry:`HOLA}}}。它不认为对象是字符串,因为(如果你的RePrP()已经被正确复制/粘贴)它不是字符串,它是字典。尝试打印类型(trans\u text)
-1这是一个非常幼稚的解决方案,甚至可能根本就不是问题!当Google表面上发出带有错误引号的JSON字符串的根本原因尚未被调查时,它正在解决这些症状。这种解决方案会导致其他问题,例如,如果翻译内容中有单引号,则“全部替换”更改为“太多双引号”,并且其含义也发生了更改,并且还会导致解析器异常。还有没有想过如何解决这个问题?@Ananth Duari:看看我的答案。
# Your other example
trans_text = {'translations': [{'translatedText': 'fleur'}, {'translatedText': 'voiture'}]}
for x in trans_text['translations']:
print "chunk of translated text:", x['translatedText']