Search code examples
pythonsimplejson

Python JSON Google Translator parsing with Simplejson problem


I am trying to parse the Google Translation result using simplejson in Python. But I am getting the following Exception.

Traceback (most recent call last):
  File "Translator.py", line 45, in <module>
    main()
  File "Translator.py", line 41, in main
    parse_json(trans_text)
  File "Translator.py", line 29, in parse_json
    json = simplejson.loads(str(trans_text))
  File "/usr/local/lib/python2.6/dist-packages/simplejson-2.1.3-py2.6-linux-i686.egg/simplejson/__init__.py", line 385, in loads
    return _default_decoder.decode(s)
  File "/usr/local/lib/python2.6/dist-packages/simplejson-2.1.3-py2.6-linux-i686.egg/simplejson/decoder.py", line 402, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/local/lib/python2.6/dist-packages/simplejson-2.1.3-py2.6-linux-i686.egg/simplejson/decoder.py", line 418, in raw_decode
    obj, end = self.scan_once(s, idx)
simplejson.decoder.JSONDecodeError: Expecting property name: line 1 column 1 (char 1)

This is my json object looks like

{'translations': [{'translatedText': 'fleur'}, {'translatedText': 'voiture'}]}

could anyone tell me what is the problem here?


Solution

  • You are doing simplejson.loads(str(trans_text))

    trans_text is NOT a string (str or unicode) or buffer object. This is witnessed by the simplejson error message, and your report of repr(trans_text):

    This is my repr of trans text {'translations': [{'translatedText': 'hola'}]}

    trans_text is a dictionary.

    If you want to convert that into a JSON string, you need to use simplejson.dumps(), not simplejson.loads().

    If you want to use the result for something else, you just need to dig the data out e.g.

    # Your other example
    trans_text = {'translations': [{'translatedText': 'fleur'}, {'translatedText': 'voiture'}]} 
    for x in trans_text['translations']:
        print "chunk of translated text:", x['translatedText']