0

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?

Bastardo
  • 4,144
  • 9
  • 41
  • 60
Ananth Duari
  • 2,859
  • 11
  • 35
  • 42
  • where `trans_text` is coming from? You should not need neither `str()` nor `.replace()` calls. – jfs Apr 12 '11 at 08:13
  • yah, but Python is not supporting single quotes. Hence I need to replace all with double quotes. – Ananth Duari Apr 12 '11 at 08:43
  • If your text is in JSON format (as defined by http://json.org) then strings must be already in double quotes. Correct JSON text can contain any Unicode character therefore `str()` will fail on any character that can't be encoded using `sys.getdefaultencoding()`. – jfs Apr 12 '11 at 09:33

2 Answers2

1

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'])
Andrey Sboev
  • 7,454
  • 1
  • 20
  • 37
0

json['translations'] is a list of objects. To extract the 'translatedText' property, you could use itemgetter:

from operator import itemgetter

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

See the implementation of detect_language_v2() for another usage example.

Community
  • 1
  • 1
jfs
  • 399,953
  • 195
  • 994
  • 1,670