I am trying to extract the JSON object in python using Simplejson. But I am getting the following error.
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
This is my JSON
object looks like,
{'translations': [{'translatedText': 'fleur'}, {'translatedText': 'voiture'}]}
and this is my python piece of code for it.
def parse_json(trans_text):
json = simplejson.loads(str(trans_text).replace("'", '"'))
result = json['translations']['translatedText']
print result
any idea on it?
json['translations']
is a list by your definition, so its indices must be integers
to get a list of translations:
translations = [x['translatedText'] for x in json['translations']]
another way:
translations = map(lambda x: x['translatedText'], json['translations'])