Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Saving JSON Files as UTF-8

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"}

like image 500
user2334258 Avatar asked Apr 30 '13 02:04

user2334258


People also ask

How do I save JSON data in Python?

Saving a JSON File in Python Python supports JSON through a built-in package called json . The text in JSON is done through quoted-string which contains the value in key-value mapping within { } . This module provides a method called dump() which converts the Python objects into appropriate json objects.

Can JSON have UTF-8?

The JSON spec requires UTF-8 support by decoders. As a result, all JSON decoders can handle UTF-8 just as well as they can handle the numeric escape sequences. This is also the case for Javascript interpreters, which means JSONP will handle the UTF-8 encoded JSON as well.

Does Python have native support for JSON?

Python Supports JSON Natively! Python comes with a built-in package called json for encoding and decoding JSON data.


1 Answers

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.

like image 160
user3194532 Avatar answered Sep 17 '22 11:09

user3194532