Frage

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

War es hilfreich?

Lösung

Your data is escaped.

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

should give you desired results:

Out[12]: {'reason': 'Record already exists.', 'status': 'failed'}

Andere Tipps

The solution here would be to figure out why your file is being doubly JSON encoded in the first place, but given that data passing it through json.loads twice is the right approach.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top