unix - Comment puis-je imprimer JSON dans un script shell

Mots clés : jsonunixcommand-lineformatpretty-print

meilleur 5 Réponses unix - Comment puis-je imprimer JSON dans un script shell

vote vote

90

echo '{"foo": "lorem", "bar": "ipsum"}' | python -m json.tool 
python -m json.tool my_json.json 
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 } 
vote vote

89

$ jq --color-output . file1.json file1.json | less -R  $ command_with_json_output | jq .  $ jq # stdin/"interactive" mode, just enter some JSON  $ jq <<< '{ "foo": "lorem", "bar": "ipsum" }' {   "bar": "ipsum",   "foo": "lorem" } 
$ jq '.foo' <<< '{ "foo": "lorem", "bar": "ipsum" }' "lorem" 
vote vote

73

// Indent with 4 spaces JSON.stringify({"foo":"lorem","bar":"ipsum"}, null, 4);  // Indent with tabs JSON.stringify({"foo":"lorem","bar":"ipsum"}, null, '\t'); 
$ node -e "console.log(JSON.stringify(JSON.parse(process.argv[1]), null, '\t'));" \   '{"foo":"lorem","bar":"ipsum"}' 
{     "foo": "lorem",     "bar": "ipsum" } 
$ 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));\  });\ " 
vote vote

69

underscore -i data.json print 
cat data.json | underscore print 
cat data.json | underscore print --outfmt pretty 
vote vote

50

echo '{"test":1,"test2":2}' | python -mjson.tool 
echo '{"test":1,"test2":2}' | python -c 'import sys,json;data=json.loads(sys.stdin.read()); print data["test"]' 
python -mjson.tool filename.json 
curl -X GET -H "Authorization: Token wef4fwef54te4t5teerdfgghrtgdg53" http://testsite/api/ | python -mjson.tool 

Questions similaires