Take this base64-encoded JSON string generated from JavaScript using JSON.stringify
and btoa
:
btoa(JSON.stringify({"é": "è"})) "eyLpIjoi6CJ9"
I’m trying to decode it from Python. I’m doing:
>>> import base64 >>> import json >>> json.loads(base64.b64decode("eyLpIjoi6CJ9"))
I’m getting a UnicodeDecodeError
:
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe9 in position 2: invalid continuation byte
What is the right way to properly decode this in Python?
Note: I’m using base64 encoding so this can be safely passed as an URL query string parameter.
Thanks!
Advertisement
Answer
You can also do in JavaScript
btoa(unescape(encodeURIComponent(JSON.stringify({"é": "è"})))) base64 output: eyLDqSI6IsOoIn0=
though I think btoa works on just the extended ascii table, not all unicode characters.
Then in Python
json.loads(base64.b64decode("eyLDqSI6IsOoIn0=") prints: {'é': 'è'}