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 に答える