简体   繁体   中英

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?

问题在于simplejson支持使用双引号编码的字符串而不是单引号编码的字符串的json,因此,天真的解决方案可能是

json.loads(jsonstring.replace("'", '"'))

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 eg

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

JSON syntax doesn't support full syntax of JavaScript. Unlike JavaScript, JSON strings and attribute names have to be double-quoted.

string ::= "" | " chars "

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM