joe smith
joe smith

Reputation: 57

Read malformed JSON in Python

I have a malformed(?) JSON file as follows:

file.json:

{u'results': [{u'status': u'OK', u'time': 199, u'name': u'Macap\xe1'}]}

I've tried using json.loads() to read this data, but it doesn't want to accept the unicode. I've tried decoding with .decode('utf-8') but that doesn't convert the \xe1 to the accented a.

Any help on the proper magic to decode this and parse in json would be amazing.

Thank you!

p.s. I'm working in Python 2.7

Upvotes: 0

Views: 2048

Answers (1)

kindall
kindall

Reputation: 184375

That's not even malformed JSON, it's a Python dictionary literal. A good way to decode it is using ast.literal_eval (as this will make sure it can't contain anything dangerous):

import ast

txt = r"{u'results': [{u'status': u'OK', u'time': 199, u'name': u'Macap\xe1'}]}"
obj = ast.literal_eval(txt)

Upvotes: 4

Related Questions