Python JSON 谷歌翻译提取问题

0 投票
2 回答
816 浏览
提问于 2025-04-16 15:33

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

json['translations'] 是一个包含多个对象的列表。如果你想提取其中的 'translatedText' 属性,可以使用 itemgetter 这个工具。

from operator import itemgetter

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

你可以查看 detect_language_v2() 的实现,里面有另一个使用示例。

1

json['translations'] 是一个列表,根据你的定义,所以它的索引必须是整数。

要获取翻译列表,可以这样做:

translations = [x['translatedText'] for x in json['translations']]

还有一种方法:

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

撰写回答