我试图使用Simplejson在python中提取JSON对象。但是我得到以下错误:
Traceback (most recent call last):
File "Translator.py", line 42, in <module>
main()
File "Translator.py", line 38, in main
parse_json(trans_text)
File "Translator.py", line 27, in parse_json
result = json['translations']['translatedText']
TypeError: list indices must be integers, not str
这是我的JSON
对象的样子,
{'translations': [{'translatedText': 'fleur'}, {'translatedText': 'voiture'}]}
这是我的python代码
def parse_json(trans_text):
json = simplejson.loads(str(trans_text).replace("'", '"'))
result = json['translations']['translatedText']
print result
有什么想法吗?
根据您的定义,json['translations']
是一个列表,因此它的索引必须是整数
获取翻译列表:
translations = [x['translatedText'] for x in json['translations']]
的另一种方法:
translations = map(lambda x: x['translatedText'], json['translations'])
json['translations']
是对象列表。要提取'translatedText'
属性,可以使用itemgetter
:
from operator import itemgetter
print map(itemgetter('translatedText'), json['translations'])
参见detect_language_v2()
的实现以获得另一个用法示例。