Decode the JSON complex in Python

I have a JSON object created in PHP, this JSON object contains another escaped JSON string in one of its cells:

php> $ insidejson = array ('foo' => 'bar', 'foo1' => 'bar1');
php> $ arr = array ('a' => array ('a1' => json_encode ($ insidejson)));
php> echo json_encode ($ arr);
{"a": {"a1": "{\" foo \ ": \" bar \ ", \" foo1 \ ": \" bar1 \ "}"}}

Then, using Python, I try to deactivate it using simplejson:

>>> import simplejson as json
>>> json.loads ('{"a": {"a1": "{\" foo \ ": \" bar \ ", \" foo1 \ ": \" bar1 \ "}"}}')

This fails with the following error:

Traceback (most recent call last):
  File "", line 1, in?
  File "build / bdist.linux-i686 / egg / simplejson / __ init__.py", line 307, in loads
  File "build / bdist.linux-i686 / egg / simplejson / decoder.py", line 335, in decode
  File "build / bdist.linux-i686 / egg / simplejson / decoder.py", line 351, in raw_decode
ValueError: Expecting, delimiter: line 1 column 14 (char 14)

How can I get this JSON object decoded in Python? Both PHP and JS successfully decode it, and I cannot change its structure, since this will require significant changes in many different components in different languages.

Thanks!

+5
source share
3 answers

'r', :

# Python 2.6.2
>>> import json
>>> s = r'{"a":{"a1":"{\"foo\":\"bar\",\"foo1\":\"bar1\"}"}}'
>>> json.loads(s)
{u'a': {u'a1': u'{"foo":"bar","foo1":"bar1"}'}}

, , : . ( , .) , , , , , .

+9

, simplejson "".

+1

If you want to insert a backslash in a string, it needs to escape itself.

import simplejson as json
json.loads('{"a":{"a1":"{\\"foo\\":\\"bar\\",\\"foo1\\":\\"bar1\\"}"}}')

I tested it, and Python handles this input just fine - except that I used the json module included in the standard library ( import json, Python 3.1).

+1
source

All Articles