¿Cómo imprimir un archivo JSON?


Tengo un archivo JSON que es un lío que quiero prettyprint? ¿cuál es la forma más fácil de hacer esto en python? Sé que PrettyPrint toma un "objeto", que creo que puede ser un archivo, pero no se como pasar un archivo in simplemente usando el nombre del archivo no funciona.

Author: martineau, 2012-10-18

7 answers

El módulo json ya implementa una impresión bastante básica con el parámetro indent:

>>> import json
>>>
>>> your_json = '["foo", {"bar":["baz", null, 1.0, 2]}]'
>>> parsed = json.loads(your_json)
>>> print json.dumps(parsed, indent=4, sort_keys=True)
[
    "foo", 
    {
        "bar": [
            "baz", 
            null, 
            1.0, 
            2
        ]
    }
]

Para analizar un archivo, use json.load:

with open('filename.txt', 'r') as handle:
    parsed = json.load(handle)
 1005
Author: Blender,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-10-17 21:54:12

Puede hacer esto en la línea de comandos:

cat some.json | python -m json.tool

(como ya se mencionó en los comentarios a la pregunta).

En realidad python no es mi herramienta favorita en lo que respecta al procesamiento json en la línea de comandos. Para una impresión bastante simple está bien, pero si desea manipular el json puede complicarse demasiado. Pronto tendría que escribir un archivo de script separado, podría terminar con mapas cuyas claves son u "some-key" (python unicode), lo que hace que la selección de campos sea más difícil y realmente no va en la dirección de la impresión bonita.

Utilizo jq. Lo anterior se puede hacer con:

cat some.json | jq ''

Y obtienes colores como un bono (y una extensibilidad mucho más fácil).

 200
Author: Gismo Ranas,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-09-07 08:48:24

Pygmentize + Python json.tool = Pretty Print con Resaltado de sintaxis

Pygmentize es una herramienta asesina. Vea esto.

Combino python json.herramienta con pigmentización

echo '{"foo": "bar"}' | python -m json.tool | pygmentize -l json

Consulte el enlace anterior para ver las instrucciones de instalación de pygmentize.

Una demostración de esto está en la imagen de abajo:

demo

 39
Author: Shubham Chaudhary,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-01-30 09:20:59

Usa esta función y no te preocupes por tener que recordar si tu JSON es str o dict de nuevo - solo mira la bonita impresión:

import json

def pp_json(json_thing, sort=True, indents=4):
    if type(json_thing) is str:
        print(json.dumps(json.loads(json_thing), sort_keys=sort, indent=indents))
    else:
        print(json.dumps(json_thing, sort_keys=sort, indent=indents))
    return None

pp_json(your_json_string_or_dict)
 30
Author: zelusp,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-06-14 03:53:03

Podría usar el pprint incorporado.

Cómo puede leer el archivo con datos json e imprimirlo.

import json
import pprint

with open('filename.txt', 'r') as f:
    data = f.read()
    json_data = json.loads(data)

pprint.pprint(json_data)
 17
Author: ikreb,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-08-28 15:30:44

Para poder imprimir bastante desde la línea de comandos y poder tener control sobre la sangría, etc. puede configurar un alias similar a este:

alias jsonpp="python -c 'import sys, json; print json.dumps(json.load(sys.stdin), sort_keys=True, indent=2)'"

Y luego use el alias de una de estas maneras:

cat myfile.json | jsonpp
jsonpp < myfile.json
 8
Author: V P,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-03-28 14:58:37

Aquí hay un ejemplo simple de impresión bonita JSON a la consola de una manera agradable en Python, sin requerir que el JSON esté en su computadora como un archivo local:

import pprint
import json 
from urllib.request import urlopen # (Only used to get this example)

# Getting a JSON example for this example 
r = urlopen("https://mdn.github.io/fetch-examples/fetch-json/products.json")
text = r.read() 

# To print it
pprint.pprint(json.loads(text))
 4
Author: David Liu,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-01-23 08:19:48