PHP – Decodes complex JSON in Python

Decodes complex JSON in Python… here is a solution to the problem.

Decodes complex JSON in Python

I created a JSON object in PHP that contains another escaped JSON string in one of the 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 tried to decode it using simplejson:

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

Failed 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 do I decode this JSON object in Python? PHP and JS both decoded it successfully, and I couldn’t change its structure because that would require breaking changes to many different components in different languages.

Thanks!

Solution

Try prefixing your string with ‘r’ to make it the original string:

# 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"}'}}

What Alex said below is true: you can double the slash. (When I started my answer, his answer was not released.) I think it’s simpler to use the original string, if only because it’s a language feature that means the same thing and is harder to go wrong.

Related Problems and Solutions