print JSON in a (Unix) shell script?

Is there a (Unix) shell script to format JSON in human-readable form?

Basically, I want it to transform the following:

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

... into something like this:

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

With Python 2.6+ you can just do:

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

or, if the JSON is in a file, you can do:

python -m json.tool my_json.json

if the JSON is from an internet source such as an API, you can use

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

For convenience in all of these cases you can make an alias:

alias prettyjson='python -m json.tool'

For even more convenience with a bit more typing to get it ready:

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

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

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

for all the above cases. You can put this in .bashrc and it will be available every time in shell. Invoke it like prettyjson_s '{"foo": "lorem", "bar": "ipsum"}' .


You can use: jq

It's very simple to use and it works great! It can handle very large JSON structures, including streams. You can find their tutorials here.

Here is an example:

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

Or in other words:

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

I use the "space" argument of [JSON.stringify ]1 to pretty-print JSON in JavaScript.

Examples:

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

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

From the Unix command-line with nodejs, specifying json on the command line:

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

Returns:

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

From the Unix command-line with Node.js, specifying a filename that contains JSON, and using an indent of four spaces:

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

Using a pipe:

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));
 });
"
链接地址: http://www.djcxy.com/p/126.html

上一篇: 什么是JSONP?

下一篇: 在(Unix)shell脚本中打印JSON?