2012-02-01 17 views
43

¿Alguien puede sugerir cómo puedo embellecer JSON en Python o a través de la línea de comandos?¿Cómo embellecer JSON en Python?

El único embellecedor JSON en línea que podría hacerlo fue: http://jsonviewer.stack.hu/.

Necesito usarlo desde dentro de Python, sin embargo.

Esta es mi conjunto de datos:

{ "head": {"vars": [ "address" , "description" ,"listprice" ]} , "results": { "bindings": [ 
    { 
     "address" : { "type":"string", "value" : " Dyne Road, London NW6"}, 
      "description" :{ "type":"string", "value" : "6 bed semi detached house"}, 
      "listprice" : { "type":"string", "value" : "1,150,000"} 
    } 
    , 
     { 
      "address" : { "type":"string", "value" : " Tweedy Road, Bromley BR1"}, 
      "description" :{ "type":"string", "value" : "5 bed terraced house"}, 
      "listprice" : { "type":"string", "value" : "550,000"} 
     } 
    , 
     { 
      "address" : { "type":"string", "value" : " Vera Avenue, London N21"}, 
      "description" :{ "type":"string", "value" : "4 bed detached house"}, 
      "listprice" : { "type":"string", "value" : " 

       995,000 


        "} 
     } 
    , 
     { 
      "address" : { "type":"string", "value" : " Wimbledon Park Side, London SW19"}, 
      "description" :{ "type":"string", "value" : "3 bedroom property for sale"}, 
      "listprice" : { "type":"string", "value" : " 

       1,250,000 


        "} 
     } 
    , 
     { 
      "address" : { "type":"string", "value" : " Westbere Road, West Hampstead, London NW2"}, 
      "description" :{ "type":"string", "value" : "5 bedroom semi detached house for sale"}, 
      "listprice" : { "type":"string", "value" : " 

       1,250,000 


        "} 
     } 
    , 
     { 
      "address" : { "type":"string", "value" : " The Avenue, Hatch End, Pinner HA5"}, 
      "description" :{ "type":"string", "value" : "5 bedroom detached house for sale"}, 
      "listprice" : { "type":"string", "value" : " 

       1,250,000 


        "} 
     } 
    , 
     { 
      "address" : { "type":"string", "value" : " Princes Park Avenue, London NW11"}, 
      "description" :{ "type":"string", "value" : "4 bedroom detached house for sale"}, 
      "listprice" : { "type":"string", "value" : " 

       1,250,000 


        "} 
     } 
    , 
     { 
      "address" : { "type":"string", "value" : " Canons Drive, Edgware HA8"}, 
      "description" :{ "type":"string", "value" : "4 bedroom detached house for sale"}, 
      "listprice" : { "type":"string", "value" : " 

       1,250,000 


        "} 
     } 
    , 
     { 
      "address" : { "type":"string", "value" : " Westbere Road, West Hampstead NW2"}, 
      "description" :{ "type":"string", "value" : "5 bedroom property for sale"}, 
      "listprice" : { "type":"string", "value" : " 

       1,250,000 


        "} 
     } 
    , 
     { 
      "address" : { "type":"string", "value" : " Haymills Estate, Ealing, London"}, 
      "description" :{ "type":"string", "value" : "5 bedroom property for sale"}, 
      "listprice" : { "type":"string", "value" : " 

       1,250,000 


        "} 
     } 
    , 
     { 
      "address" : { "type":"string", "value" : " Dene Terrace Woodclyffe Drive, Chislehurst, Kent BR7"}, 
      "description" :{ "type":"string", "value" : "5 bedroom terraced house for sale"}, 
      "listprice" : { "type":"string", "value" : " 

       1,250,000 


        "} 
     } 
    , 
     { 
      "address" : { "type":"string", "value" : " Dene Terrace Woodclyffe Drive, Chislehurst, Kent BR7"}, 
      "description" :{ "type":"string", "value" : "5 bedroom semi detached house for sale"}, 
      "listprice" : { "type":"string", "value" : " 

       1,250,000 


        "} 
     } 
    , 
     { 
      "address" : { "type":"string", "value" : " Northwick Close, St John's Wood NW8"}, 
      "description" :{ "type":"string", "value" : "3 bedroom property for sale"}, 
      "listprice" : { "type":"string", "value" : " 

       1,250,000 


        "} 
     } 
    , 
     { 
      "address" : { "type":"string", "value" : " Claremont Gardens, Surbiton KT6"}, 
      "description" :{ "type":"string", "value" : "13 bedroom property for sale"}, 
      "listprice" : { "type":"string", "value" : " 

       1,250,000 


        "} 
     } 
    , 
     { 
      "address" : { "type":"string", "value" : " Dene Terrace Woodclyffe Drive, Chislehurst, Kent BR7"}, 
      "description" :{ "type":"string", "value" : "5 bedroom end terrace house for sale"}, 
      "listprice" : { "type":"string", "value" : " 

       1,250,000 


        "} 
     } 
    , 
     { 
      "address" : { "type":"string", "value" : " Stamford Road, London N1"}, 
      "description" :{ "type":"string", "value" : "4 bedroom terraced house for sale"}, 
      "listprice" : { "type":"string", "value" : " 

       1,250,000 


        "} 
     } 
    , 
     { 
      "address" : { "type":"string", "value" : " Stanhope Avenue, London N3"}, 
      "description" :{ "type":"string", "value" : "6 bedroom property for sale"}, 
      "listprice" : { "type":"string", "value" : " 

       1,250,000 


        "} 
     } 
    , 
     { 
      "address" : { "type":"string", "value" : " Haymills Estate, Ealing, London"}, 
      "description" :{ "type":"string", "value" : "5 bedroom property for sale"}, 
      "listprice" : { "type":"string", "value" : " 

       1,250,000 


        "} 
     } 
    , 
     { 
      "address" : { "type":"string", "value" : " Elms Crescent, London SW4"}, 
      "description" :{ "type":"string", "value" : "5 bedroom property for sale"}, 
      "listprice" : { "type":"string", "value" : " 

       1,250,000 


        "} 
     } 
    , 
     { 
      "address" : { "type":"string", "value" : " Princes Park Avenue, London NW11"}, 
      "description" :{ "type":"string", "value" : "4 bedroom property for sale"}, 
      "listprice" : { "type":"string", "value" : " 

       1,250,000 


        "} 
     } 
    , 
     { 
      "address" : { "type":"string", "value" : " Abbeville Road, London SW4"}, 
      "description" :{ "type":"string", "value" : "4 bedroom property for sale"}, 
      "listprice" : { "type":"string", "value" : " 

       1,250,000 


        "} 
     } 
    , 
     { 
      "address" : { "type":"string", "value" : " Canons Drive, Edgware HA8"}, 
      "description" :{ "type":"string", "value" : "4 bedroom detached house for sale"}, 
      "listprice" : { "type":"string", "value" : " 

       1,250,000 


        "} 
     } 
    , 
     { 
      "address" : { "type":"string", "value" : " Henson Avenue, Willesdon Green NW2"}, 
      "description" :{ "type":"string", "value" : "5 bedroom property for sale"}, 
      "listprice" : { "type":"string", "value" : " 

       1,250,000 


        "} 
     } 
    , 
     { 
      "address" : { "type":"string", "value" : " Woodstock Road, London NW11"}, 
      "description" :{ "type":"string", "value" : "5 bedroom property for sale"}, 
      "listprice" : { "type":"string", "value" : " 

       1,250,000 


        "} 
     } 
    , 
     { 
      "address" : { "type":"string", "value" : " Tamworth Street, London SW6"}, 
      "description" :{ "type":"string", "value" : "5 bedroom property for sale"}, 
      "listprice" : { "type":"string", "value" : " 

       1,250,000 


        "} 
     } 
    , 
     { 
      "address" : { "type":"string", "value" : " Stanhope Avenue, Finchley, London"}, 
      "description" :{ "type":"string", "value" : "5 bedroom semi detached house for sale"}, 
      "listprice" : { "type":"string", "value" : " 

       1,250,000 


        "} 
     } 
    , 
     { 
      "address" : { "type":"string", "value" : " The Old Burlington, Church Street, London W4"}, 
      "description" :{ "type":"string", "value" : "3 bedroom property for sale"}, 
      "listprice" : { "type":"string", "value" : " 

       1,250,000 


        "} 
     } 
    , 
     { 
      "address" : { "type":"string", "value" : " Ebury Close, Northwood HA6"}, 
      "description" :{ "type":"string", "value" : "4 bedroom detached house for sale"}, 
      "listprice" : { "type":"string", "value" : " 

       1,250,000 


        "} 
     } 
    , 
     { 
      "address" : { "type":"string", "value" : " Middleton Road, London NW11"}, 
      "description" :{ "type":"string", "value" : "4 bedroom property for sale"}, 
      "listprice" : { "type":"string", "value" : " 

       1,250,000 


        "} 
     } 
    , 
     { 
      "address" : { "type":"string", "value" : " Henson Avenue, Willesden Green NW2"}, 
      "description" :{ "type":"string", "value" : "5 bedroom property for sale"}, 
      "listprice" : { "type":"string", "value" : " 

       1,250,000 


        "} 
     } 
    , 
     { 
      "address" : { "type":"string", "value" : " Huron Road, London SW17"}, 
      "description" :{ "type":"string", "value" : "6 bedroom property for sale"}, 
      "listprice" : { "type":"string", "value" : " 

       1,250,000 


        "} 
     } 
    , 
     { 
      "address" : { "type":"string", "value" : " Corringway, Ealing W5"}, 
      "description" :{ "type":"string", "value" : "5 bedroom detached house for sale"}, 
      "listprice" : { "type":"string", "value" : " 

       1,250,000 


        "} 
     } 
    , 
     { 
      "address" : { "type":"string", "value" : " Woodlands Avenue, New Malden KT3"}, 
      "description" :{ "type":"string", "value" : "5 bedroom detached house for sale"}, 
      "listprice" : { "type":"string", "value" : " 

       1,250,000 


        "} 
     } 
    , 
     { 
      "address" : { "type":"string", "value" : " Gunnersbury Park Area, Ealing, London"}, 
      "description" :{ "type":"string", "value" : "6 bedroom property for sale"}, 
      "listprice" : { "type":"string", "value" : " 

       1,250,000 


        "} 
     } 
    , 
     { 
      "address" : { "type":"string", "value" : " Blenheim Gardens, London, Brent NW2"}, 
      "description" :{ "type":"string", "value" : "6 bedroom property for sale"}, 
      "listprice" : { "type":"string", "value" : " 

       1,250,000 


        "} 
     } 
    , 
     { 
      "address" : { "type":"string", "value" : " Creighton Road, London NW6"}, 
      "description" :{ "type":"string", "value" : "4 bedroom terraced house for sale"}, 
      "listprice" : { "type":"string", "value" : " 

       1,250,000 


        "} 
     } 
    , 
     { 
      "address" : { "type":"string", "value" : " Plaistow Lane, Bromley BR1"}, 
      "description" :{ "type":"string", "value" : "7 bedroom detached house for sale"}, 
      "listprice" : { "type":"string", "value" : " 

       1,250,000 


        "} 
     } 
    , 
     { 
      "address" : { "type":"string", "value" : " Greenfield Gardens, London NW2"}, 
      "description" :{ "type":"string", "value" : "4 bedroom property for sale"}, 
      "listprice" : { "type":"string", "value" : " 

       1,250,000 


        "} 
     } 
    , 
     { 
      "address" : { "type":"string", "value" : " Hendon Avenue, London N3"}, 
      "description" :{ "type":"string", "value" : "3 bedroom detached house for sale"}, 
      "listprice" : { "type":"string", "value" : " 

       1,250,000 


        "} 
     } 
    , 
     { 
      "address" : { "type":"string", "value" : " Peckham Park Road, London SE15"}, 
      "description" :{ "type":"string", "value" : "6 bedroom semi detached house for sale"}, 
      "listprice" : { "type":"string", "value" : " 

       1,250,000 


        "} 
     } 
    , 
     { 
      "address" : { "type":"string", "value" : " Woodclyffe Drive, Chislehurst BR7"}, 
      "description" :{ "type":"string", "value" : "5 bedroom house for sale"}, 
      "listprice" : { "type":"string", "value" : " 

       From 1,250,000 


        "} 
     } 
    , 
     { 
      "address" : { "type":"string", "value" : " Highwood Hill, Mill Hill, London"}, 
      "description" :{ "type":"string", "value" : "5 bedroom detached house for sale"}, 
      "listprice" : { "type":"string", "value" : " 

       1,250,000 


        "} 
     } 
    , 
     { 
      "address" : { "type":"string", "value" : " Stanhope Avenue, London N3"}, 
      "description" :{ "type":"string", "value" : "5 bedroom semi detached house for sale"}, 
      "listprice" : { "type":"string", "value" : " 

       1,250,000 


        "} 
     } 
    , 
     { 
      "address" : { "type":"string", "value" : " Kersley Mews, London SW11"}, 
      "description" :{ "type":"string", "value" : "3 bedroom mews for sale"}, 
      "listprice" : { "type":"string", "value" : " 

       1,250,000 


        "} 
     } 
    , 
     { 
      "address" : { "type":"string", "value" : " Ebury Close, Northwood HA6"}, 
      "description" :{ "type":"string", "value" : "4 bedroom detached house for sale"}, 
      "listprice" : { "type":"string", "value" : " 

       1,250,000 


        "} 
     } 
    , 
     { 
      "address" : { "type":"string", "value" : " Ellesmere Road, Chiswick W4"}, 
      "description" :{ "type":"string", "value" : "6 bedroom detached house for sale"}, 
      "listprice" : { "type":"string", "value" : " 

       1,250,000 


        "} 
     } 
    , 
     { 
      "address" : { "type":"string", "value" : " The Avenue, Hatch End, Pinner, Middlesex"}, 
      "description" :{ "type":"string", "value" : "5 bedroom detached house for sale"}, 
      "listprice" : { "type":"string", "value" : " 

       1,250,000 


        "} 
     } 
    , 
     { 
      "address" : { "type":"string", "value" : " Wandsworth, London SW18"}, 
      "description" :{ "type":"string", "value" : "6 bedroom semi detached house for sale"}, 
      "listprice" : { "type":"string", "value" : " 

       1,250,000 


        "} 
     } 
    , 
     { 
      "address" : { "type":"string", "value" : " Carlton Road, New Malden KT3"}, 
      "description" :{ "type":"string", "value" : "4 bedroom detached house for sale"}, 
      "listprice" : { "type":"string", "value" : " 

       1,250,000 


        "} 
     } 
    , 
     { 
      "address" : { "type":"string", "value" : " St Mary's Mews, Ealing W5"}, 
      "description" :{ "type":"string", "value" : "3 bedroom property for sale"}, 
      "listprice" : { "type":"string", "value" : " 

       1,250,000 


        "} 
     } 
    , 
     { 
      "address" : { "type":"string", "value" : " Ritherdon Road, Balham, London SW17"}, 
      "description" :{ "type":"string", "value" : "5 bedroom semi detached house for sale"}, 
      "listprice" : { "type":"string", "value" : " 

       1,250,000 


        "} 
     } 
    , 
     { 
      "address" : { "type":"string", "value" : " Goldsmith Avenue, London W3"}, 
      "description" :{ "type":"string", "value" : "5 bedroom property for sale"}, 
      "listprice" : { "type":"string", "value" : " 

       1,250,000 


        "} 
     } 
    , 
     { 
      "address" : { "type":"string", "value" : " Plaistow Lane, Bromley, Kent BR1"}, 
      "description" :{ "type":"string", "value" : "7 bedroom detached house for sale"}, 
      "listprice" : { "type":"string", "value" : " 

       1,250,000 


        "} 
     } 
    ] } } 

Respuesta

90

Desde la línea de comandos:

echo '{"one":1,"two":2}' | python -mjson.tool 

que da salida:

{ 
    "one": 1, 
    "two": 2 
} 

Programmtically, el lenguaje Python describes pretty-printing JSON:

>>> import json 
>>> print json.dumps({'4': 5, '6': 7}, sort_keys=True, indent=4) 
{ 
    "4": 5, 
    "6": 7 
} 
7

El comando CLI que he usado con el pitón de esto es:

cat myfile.json | python -mjson.tool 

usted debería ser capaz de encontrar más información aquí:

http://docs.python.org/library/json.html

+0

Eso es otro ejemplo desafortunado de abuso felina. El mismo resultado se puede lograr sin crear un proceso separado y un montón de copia de memoria gratuita con un simple 'python -mjson.tool

+0

¿Tal vez me gusta alimentar a mis gatos? : P – Herms

18

Utilice el argumento indent de la función dumps en el json module.

A partir de los documentos:

>>> import json 
>>> print json.dumps({'4': 5, '6': 7}, sort_keys=True, indent=4) 
{ 
    "4": 5, 
    "6": 7 
} 
1

sus datos están mal formados. Los campos de valor en particular tienen numerosos espacios y nuevas líneas. Los formateadores automatizados no funcionarán en esto, ya que no modificarán los datos reales. A medida que genera los datos para la salida, filtéelos según sea necesario para evitar los espacios.

4
alias jsonp='pbpaste | python -m json.tool' 

Esto imprimirá bastante JSON que está en el portapapeles en OSX. Simplemente cópielo y luego llame al alias desde un indicador de Bash.

15

Trate underscore-cli:

cat myfile.json | underscore print --color 

Es una herramienta bastante ingeniosa que elegantemente se puede hacer un montón de manipulación de datos estructurados, ejecutar fragmentos js, llenar las plantillas, etc. Es ridículamente bien documentados, pulido, y listo para un uso serio. Y lo escribí :)

0

Puede canalizar la salida a jq.Si script en Python contiene algo así como

print json.dumps(data) 

entonces se puede disparar:

python foo.py | jq '.' 
0

Con jsonlint (como xmllint):

aptitude install python-demjson 
jsonlint -f foo.json 
11

Una solución mínima en Python que los colores de datos JSON suministrado a través de la línea de comando:

import sys 
import json 
from pygments import highlight, lexers, formatters 

formatted_json = json.dumps(json.loads(sys.argv[1]), indent=4) 
colorful_json = highlight(unicode(formatted_json, 'UTF-8'), lexers.JsonLexer(), formatters.TerminalFormatter()) 
print(colorful_json) 

Inspirado por pjson mencionado anteriormente. Este código necesita pygments para ser instalado.

Ejemplo de salida:

enter image description here

+0

Muy útil. Exactamente lo que estaba buscando: embellecer las salidas de datos JSON en ipython. Gracias. – noumenon

4

Parece que jsbeautifier código abierto sus herramientas y los empaquetan como librerías de Python y JS, y como herramientas de CLI. No parece que llamen a un servicio web, pero no lo revisé demasiado de cerca. Consulte el github repo con las instrucciones de instalación.


Desde sus documentos para CLI Python y uso de la biblioteca:

para embellecer el uso de Python:

$ pip install jsbeautifier 
$ js-beautify file.js 

salida embellecido va a stdout.

Para utilizar jsbeautifier como una biblioteca es simple:

import jsbeautifier 
res = jsbeautifier.beautify('your javascript string') 
res = jsbeautifier.beautify_file('some_file.js') 

... o, para especificar algunas opciones:

opts = jsbeautifier.default_options() 
opts.indent_size = 2 
res = jsbeautifier.beautify('some javascript', opts) 

Si desea pasar una cadena en lugar de una nombre de archivo, y está utilizando bash, entonces puede usar la sustitución de proceso como sigue:

$ js-beautify <(echo '{"some": "json"}') 
1

Primero instale Pygments

continuación

echo '<some json>' | python -m json.tool | pygmentize -l json