Alex Tonkonozhenko
Alex Tonkonozhenko

Reputation: 1574

Parsing JSON with bytes in Python

I have some external service that sends me next json:

json_str = b'{"a": "\xc3-----\xa4-----\x13"}'

When I trying to parse it, I get next error:

----> 1 json.loads(json_str)
ValueError: Invalid control character at: line 1 column 20 (char 19)

I managed to parse it correctly using next command:

In [37]: eval(json_str)
Out[37]: {'a': '\xc3-----\xa4-----\x13'}

Are there any ideas on how to parse it in another way?

Upvotes: 3

Views: 1582

Answers (1)

Albin Paul
Albin Paul

Reputation: 3419

I found a way using .decode and the json.loads functions.

Hope this helps.

>>> json.loads(json_str.decode("latin-1"), strict=False)
{u'a': u'\xc3-----\xa4-----\x13'}

The output is still in unicode

References

json.loads error

decode error

Upvotes: 3

Related Questions