Вопрос: Как я могу напечатать JSON в сценарии оболочки (Unix)?


Есть ли сценарий оболочки Unix для форматирования JSON в удобочитаемой форме?

В принципе, я хочу, чтобы он преобразовал следующее:

{ "foo": "lorem", "bar": "ipsum" }

... в нечто подобное:

{
    "foo": "lorem",
    "bar": "ipsum"
}

2468


источник


Ответы:


С Python 2.6+ вы можете просто сделать:

echo '{"foo": "lorem", "bar": "ipsum"}' | python -m json.tool

или, если JSON находится в файле, вы можете сделать:

python -m json.tool my_json.json

если JSON находится из интернет-источника, такого как API, вы можете использовать

curl http://my_url/ | python -m json.tool

Для удобства во всех этих случаях вы можете создать псевдоним:

alias prettyjson='python -m json.tool'

Для еще большего удобства с немного более типизированным, чтобы подготовить его:

prettyjson_s() {
    echo "$1" | python -m json.tool
}

prettyjson_f() {
    python -m json.tool "$1"
}

prettyjson_w() {
    curl "$1" | python -m json.tool
}

для всех вышеперечисленных случаев. Вы можете положить это в .bashrcи он будет доступен каждый раз в оболочке. Вызовите его как prettyjson_s '{"foo": "lorem", "bar": "ipsum"}',


3690



Вы можете использовать: jq

Он очень прост в использовании, и он отлично работает! Он может обрабатывать очень большие структуры JSON, включая потоки. Ты можешь найти их учебники Вот ,

Вот пример:

$ jq . <<< '{ "foo": "lorem", "bar": "ipsum" }'
{
  "bar": "ipsum",
  "foo": "lorem"
}

Или другими словами:

$ echo '{ "foo": "lorem", "bar": "ipsum" }' | jq .
{
  "bar": "ipsum",
  "foo": "lorem"
}

671



Я использую аргумент «space» JSON.stringifyдля корректной печати JSON в JavaScript.

Примеры:

// Indent with 4 spaces
JSON.stringify({"foo":"lorem","bar":"ipsum"}, null, 4);

// Indent with tabs
JSON.stringify({"foo":"lorem","bar":"ipsum"}, null, '\t');

Из командной строки Unix с nodejs, указав json в командной строке:

$ node -e "console.log(JSON.stringify(JSON.parse(process.argv[1]), null, '\t'));" \
  '{"foo":"lorem","bar":"ipsum"}'

Возвращает:

{
    "foo": "lorem",
    "bar": "ipsum"
}

Из командной строки Unix с Node.js, указав имя файла, содержащее JSON, и используя отступ из четырех пробелов:

$ node -e "console.log(JSON.stringify(JSON.parse(require('fs') \
      .readFileSync(process.argv[1])), null, 4));"  filename.json

Использование трубы:

echo '{"foo": "lorem", "bar": "ipsum"}' | node -e \
"\
 s=process.openStdin();\
 d=[];\
 s.on('data',function(c){\
   d.push(c);\
 });\
 s.on('end',function(){\
   console.log(JSON.stringify(JSON.parse(d.join('')),null,2));\
 });\
"

350



I wrote a tool that has one of the best "smart whitespace" formatters available. It produces more readable and less verbose output than most of the other options here.

underscore-cli

This is what "smart whitespace" looks like:

I may be a bit biased, but it's an awesome tool for printing and manipulating JSON data from the command-line. It's super-friendly to use and has extensive command-line help/documentation. It's a Swiss Army knife that I use for 1001 different small tasks that would be surprisingly annoying to do any other way.

Latest use-case: Chrome, Dev console, Network tab, export all as HAR file, "cat site.har | underscore select '.url' --outfmt text | grep mydomain"; now I have a chronologically ordered list of all URL fetches made during the loading of my company's site.

Pretty printing is easy:

underscore -i data.json print

Same thing:

cat data.json | underscore print

Same thing, more explicit:

cat data.json | underscore print --outfmt pretty

This tool is my current passion project, so if you have any feature requests, there is a good chance I'll address them.


321



I usually just do:

echo '{"test":1,"test2":2}' | python -mjson.tool

And to retrieve select data (in this case, "test"'s value):

echo '{"test":1,"test2":2}' | python -c 'import sys,json;data=json.loads(sys.stdin.read()); print data["test"]'

If the JSON data is in a file:

python -mjson.tool filename.json

If you want to do it all in one go with curl on the command line using an authentication token:

curl -X GET -H "Authorization: Token wef4fwef54te4t5teerdfgghrtgdg53" http://testsite/api/ | python -mjson.tool

165



Thanks to J.F. Sebastian's very helpful pointers, here's a slightly enhanced script I've come up with:

#!/usr/bin/python

"""
Convert JSON data to human-readable form.

Usage:
  prettyJSON.py inputFile [outputFile]
"""

import sys
import simplejson as json


def main(args):
    try:
        if args[1] == '-':
            inputFile = sys.stdin
        else:
            inputFile = open(args[1])
        input = json.load(inputFile)
        inputFile.close()
    except IndexError:
        usage()
        return False
    if len(args) < 3:
        print json.dumps(input, sort_keys = False, indent = 4)
    else:
        outputFile = open(args[2], "w")
        json.dump(input, outputFile, sort_keys = False, indent = 4)
        outputFile.close()
    return True


def usage():
    print __doc__


if __name__ == "__main__":
    sys.exit(not main(sys.argv))

82



With Perl, use the CPAN module JSON::XS. It installs a command line tool json_xs.

Validate:

json_xs -t null < myfile.json

Prettify the JSON file src.json to pretty.json:

< src.json json_xs > pretty.json

If you don't have json_xs, try json_pp . "pp" is for "pure perl" – the tool is implemented in Perl only, without a binding to an external C library (which is what XS stands for, Perl's "Extension System").


64



On *nix, reading from stdin and writing to stdout works better:

#!/usr/bin/env python
"""
Convert JSON data to human-readable form.

(Reads from stdin and writes to stdout)
"""

import sys
try:
    import simplejson as json
except:
    import json

print json.dumps(json.loads(sys.stdin.read()), indent=4)
sys.exit(0)

Put this in a file (I named mine "prettyJSON" after AnC's answer) in your PATH and chmod +x it, and you're good to go.


64



The JSON Ruby Gem is bundled with a shell script to prettify JSON:

sudo gem install json
echo '{ "foo": "bar" }' | prettify_json.rb

Script download: gist.github.com/3738968


63



If you use npm and Node.js, you can do npm install -g json and then pipe the command through json. Do json -h to get all the options. It can also pull out specific fields and colorize the output with -i.

curl -s http://search.twitter.com/search.json?q=node.js | json

63



UPDATE I'm using jq now as suggested in another answer. It's extremely powerful at filtering JSON, but, at its most basic, also an awesome way to pretty print JSON for viewing.

jsonpp is a very nice command line JSON pretty printer.

From the README:

Pretty print web service responses like so:

curl -s -L http://<!---->t.co/tYTq5Pu | jsonpp

and make beautiful the files running around on your disk:

jsonpp data/long_malformed.json

If you're on Mac OS X, you can brew install jsonpp. If not, you can simply copy the binary to somewhere in your $PATH.


53