Python Saving JSON Files as UTF-8
Asked Answered
A

2

29

I'm trying to output some UTF-8 characters to a JSON file.

When I save the file they're being written like this:

{"some_key": "Enviar invitaci\u00f3n privada"}

The above is valid and works. When I load the file and print 'some_key' it displays "Enviar invitación privada" in the terminal.

Is there anyway to write the JSON file with "some_key" as the encoded version, like this?

{"some_key": "Enviar invitación privada"}

Actinal answered 30/4, 2013 at 2:39 Comment(1)
Complete answer (including python 2 version) can be found here.Efferent
B
33

Set ensure_ascii to False:

>>> print json.dumps(x, ensure_ascii=False)
{"some_key": "Enviar invitación privada"}
Burgwell answered 30/4, 2013 at 2:41 Comment(2)
I'm still getting characters like: à instead of à è instead of è any suggestions?Redhanded
This does not save the data to a file!Aquarist
T
49

Using Python 3.4.3 here and using dump() instead of dumps():

    with open("example.json","w", encoding='utf-8') as jsonfile:
        json.dump(data,jsonfile,ensure_ascii=False)

is the standard way to write JSON to an UTF-8 encoded file.

If you want the escaped code points instead of the characters in your file, set ensure_ascii=True. This writes for example the Euro-character as \u20ac directly to your file.

Toadfish answered 13/3, 2016 at 9:12 Comment(0)
B
33

Set ensure_ascii to False:

>>> print json.dumps(x, ensure_ascii=False)
{"some_key": "Enviar invitación privada"}
Burgwell answered 30/4, 2013 at 2:41 Comment(2)
I'm still getting characters like: à instead of à è instead of è any suggestions?Redhanded
This does not save the data to a file!Aquarist

© 2022 - 2024 — McMap. All rights reserved.