0

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

有什么想法吗?

4

2 回答 2

1

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

获取翻译列表:

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

其他方式:

translations  = map(lambda x: x['translatedText'], json['translations'])
于 2011-04-12T07:57:17.760 回答
0

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

from operator import itemgetter

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

请参阅detect_language_v2()另一个使用示例的实现。

于 2011-04-12T08:09:37.983 回答