Python JSON谷歌翻译提取问题

时间:2011-04-12 07:45:34

标签: python json simplejson

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

关于它的任何想法?

2 个答案:

答案 0 :(得分:1)

json['translations']是您定义的列表,因此其索引必须是整数

获取翻译列表:

translations = [x['translatedText'] for x in json['translations']]
另一种方式:

translations  = map(lambda x: x['translatedText'], json['translations'])

答案 1 :(得分:0)

json['translations']是一个对象列表。要提取'translatedText'属性,您可以使用itemgetter

from operator import itemgetter

print map(itemgetter('translatedText'), json['translations'])

有关其他用法示例,请参阅detect_language_v2()的实现。