Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

json.loads() is returning a unicode object instead of a dictionary

I'm reading in json from a file on a remote server using fabric:

from StringIO import StringIO

output = StringIO()
get(file_name, output)

output = output.getvalue()

The value of output is now:

'"{\\n \\"status\\": \\"failed\\", \\n \\"reason\\": \\"Record already exists.\\"\\n}"'

When I try to parse this string to a dictionary using json.loads(output) its returns the unicode object u'{\n "status": "failed", \n "reason": "Record already exists."\n}' rather than a dictionary.

I've come up with a fairly bad fix, just passing the new unicode object back into json.loads():

json.loads(json.loads(output))

Is there any way other solution to this?

Cheers

like image 747
Dr Potato Avatar asked Mar 24 '14 02:03

Dr Potato


1 Answers

Your data is escaped.

json.loads(output.decode('string-escape').strip('"'))

should give you desired results:

Out[12]: {'reason': 'Record already exists.', 'status': 'failed'}
like image 118
m.wasowski Avatar answered Oct 20 '22 18:10

m.wasowski