Paul
Paul

Reputation: 6737

Dump json string to unicode and parse it back

I'm trying to dump unicode string containting json to the value of another JSON, pass it as a json response to API and parse it back. It looks super-trivial but I'm stuck with it.

Here is a simplified code to reproduce.

>>> s = {u'k': '123213'}
>>> d = {1: unicode(s)}
>>> d
{1: u"{u'k': '123213'}"}
>>> d[1]
u"{u'k': '123213'}"
>>> json.loads(d[1])

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 338, in loads
    return _default_decoder.decode(s)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 366, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 382, in raw_decode
    obj, end = self.scan_once(s, idx)
ValueError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)

How can I parse d[1] back to the valid json with python 2.7?

Upvotes: 0

Views: 29

Answers (1)

Rakesh
Rakesh

Reputation: 82765

Use ast module

Ex:

>>> s = {u'k': '123213'}
>>> d = {1: unicode(s)}
>>> import ast
>>> ast.literal_eval(d[1])
{u'k': '123213'}

Upvotes: 1

Related Questions