Vladislav Ladenkov Vladislav Ladenkov - 2 months ago 17
Python Question

Pretty print a JSON in Python 3.5

I want to pretty print a JSON file, but popular solutions: How to Python prettyprint a JSON file dont work for me.

Code:

import json, os

def load_data(filepath):
if not os.path.exists(filepath):
print("ACHTUNG! Incorrect path")
return None
with open(filepath, 'r') as file:
return json.load(file)


This function is OKay - it loads jason properly.
But when i want to pp it like this:

def pretty_print_json(data):
print(json.dumps(data, indent=4, sort_keys=True))
return None

if __name__ == '__main__':
pretty_print_json(load_data("data.json")) ,


it serializes the values of the dictionaries!:

[
{
"Cells": {
"Address": "\u0443\u043b\u0438\u0446\u0430 \u0410\u043a\u0430\u0434\u0435\u043c\u0438\u043a\u0430 \u041f\u0430\u0432\u043b\u043e\u0432\u0430, \u0434\u043e\u043c 10",
"AdmArea": "\u0417\u0430\u043f\u0430\u0434\u043d\u044b\u0439 \u0430\u0434\u043c\u0438\u043d\u0438\u0441\u0442\u0440\u0430\u0442\u0438\u0432\u043d\u044b\u0439 \u043e\u043a\u0440\u0443\u0433",
"ClarificationOfWorkingHours": null,
"District": "\u0440\u0430\u0439\u043e\u043d \u041a\u0443\u043d\u0446\u0435\u0432\u043e",
"IsNetObject": "\u0434\u0430",
"Name": "\u0410\u0440\u043e\u043c\u0430\u0442\u043d\u044b\u0439 \u041c\u0438\u0440",
"OperatingCompany": "\u0410\u0440\u043e\u043c\u0430\u0442\u043d\u044b\u0439 \u041c\u0438\u0440",
"PublicPhone": [
{
"PublicPhone": "(495) 777-51-95"
}


What's the problem? It's anaconda 3.5

Answer

json.dumps() produces ASCII-safe JSON by default. If you want to retain non-ASCII data as Unicode codepoints, disable that default by setting ensure_ascii=False:

print(json.dumps(data, indent=4, sort_keys=True, ensure_ascii=False))

which, for your sample data, then produces:

[
    {
        "Cells": {
            "Address": "улица Академика Павлова, дом 10",
            "AdmArea": "Западный административный округ",
            "ClarificationOfWorkingHours": null,
            "District": "район Кунцево",
            "IsNetObject": "да",
            "Name": "Ароматный Мир",
            "OperatingCompany": "Ароматный Мир",
            "PublicPhone": [
                {
                    "PublicPhone": "(495) 777-51-95"
                }

(cut off at the same point you cut things off).

Comments