json解析 - 如何在shell腳本中打印JSON?
windows jq command (20)
Pygmentize
我將Python的json.tool與pygmentize結合起來:
echo '{"foo": "bar"}' | python -m json.tool | pygmentize -g
pygmentize有一些替代品, 我在這個答案中列出了。
這是一個現場演示:
是否有(Unix)shell腳本以人類可讀的形式格式化JSON?
基本上,我希望它改變以下內容:
{ "foo": "lorem", "bar": "ipsum" }
...進入這樣的事情:
{
"foo": "lorem",
"bar": "ipsum"
}
香草巴什
一個簡單的Bash腳本( grep
/ awk
),用於漂亮的JSON打印,沒有第三方安裝:
json_pretty.sh
#/bin/bash
grep -Eo '"[^"]*" *(: *([0-9]*|"[^"]*")[^{}\["]*|,)?|[^"\]\[\}\{]*|\{|\},?|\[|\],?|[0-9 ]*,?' | awk '{if ($0 ~ /^[}\]]/ ) offset-=4; printf "%*c%s\n", offset, " ", $0; if ($0 ~ /^[{\[]/) offset+=4}'
例子:
1)在控制台中讀取文件和漂亮的打印
cat file.json | json_pretty.sh
2)使用Windows GIT Bash從文件到文件(基於UTF8):
cat fileIn.json |sh.exe json_pretty.sh > fileOut.json
JSON Ruby Gem與shell腳本捆綁在一起來美化JSON:
sudo gem install json
echo '{ "foo": "bar" }' | prettify_json.rb
腳本下載: gist.github.com/3738968
PHP版本,如果你有PHP> = 5.4。
alias prettify_json=php -E '$o = json_decode($argn); print json_encode($o, JSON_PRETTY_PRINT);'
echo '{"a":1,"b":2}' | prettify_json
jj是超快的,可以經濟地處理巨大的JSON文檔,不會弄亂有效的JSON數字,並且易於使用,例如
jj -p # for reading from STDIN
要么
jj -p -i input.json
它(2018)仍然很新,所以也許它不會按照你期望的方式處理無效的JSON,但它很容易在主要平台上安裝。
使用Perl,如果從CPAN安裝JSON::PP ,您將獲得json_pp命令。 竊取B Bycroft的example你會得到:
[[email protected] ~]$ echo '{"foo": "lorem", "bar": "ipsum"}' | json_pp
{
"bar" : "ipsum",
"foo" : "lorem"
}
值得一提的是, json_pp
預先安裝了Ubuntu 12.04(至少)和Debian /usr/bin/json_pp
在/usr/bin/json_pp
使用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
,它每次都可以在shell中使用。 像prettyjson_s '{"foo": "lorem", "bar": "ipsum"}'
一樣調用它。
只需將輸出傳輸到jq .
。
例:
twurl -H ads-api.twitter.com '.......' | jq .
在* nix上,從stdin讀取並寫入stdout更好:
#!/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)
把它放在一個文件中(我在AnC的回答中將其命名為“prettyJSON”)在你的PATH和chmod +x
,然後你就可以了。
感謝JF Sebastian的非常有用的指示,這裡有一個稍微增強的腳本我想出了:
#!/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))
我使用JSON.stringify
的“space”參數在JavaScript中漂亮地打印JSON。
例子:
// Indent with 4 spaces
JSON.stringify({"foo":"lorem","bar":"ipsum"}, null, 4);
// Indent with tabs
JSON.stringify({"foo":"lorem","bar":"ipsum"}, null, '\t');
從帶有nodejs的Unix命令行,在命令行上指定json:
$ node -e "console.log(JSON.stringify(JSON.parse(process.argv[1]), null, '\t'));" \
'{"foo":"lorem","bar":"ipsum"}'
返回:
{
"foo": "lorem",
"bar": "ipsum"
}
從帶有Node.js的Unix命令行,指定包含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));\
});\
"
我寫了一個工具,它有一個最好的“智能空白”格式化器。 它比這裡的大多數其他選項產生更可讀,更簡潔的輸出。
這就是“智能空白”的樣子:
我可能有點偏頗,但它是一個很棒的工具,用於從命令行打印和操作JSON數據。 它使用起來非常友好,並提供廣泛的命令行幫助/文檔。 這是一把瑞士軍刀,我用它來完成1001個不同的小任務,任何其他方式都令人驚訝地煩人。
最新用例:Chrome,開發控制台,網絡選項卡,全部導出為HAR文件,“cat site.har |下劃線選擇'.url' - outfmt text | grep mydomain”; 現在我有一個按時間順序列出的所有URL提取列表,在加載我公司的網站時。
漂亮的打印很簡單:
underscore -i data.json print
一樣:
cat data.json | underscore print
同樣的事情,更明確:
cat data.json | underscore print --outfmt pretty
這個工具是我目前的激情項目,所以如果您有任何功能請求,我很有可能會解決它們。
我建議使用JSON :: XS perl模塊中包含的json_xs命令行實用程序。 JSON :: XS是一個用於序列化/反序列化JSON的Perl模塊,在Debian或Ubuntu機器上你可以像這樣安裝它:
sudo apt-get install libjson-xs-perl
它顯然也可以在CPAN 。
要使用它來格式化從URL獲取的JSON,您可以使用curl或wget,如下所示:
$ curl -s http://page.that.serves.json.com/json/ | json_xs
或這個:
$ wget -q -O - http://page.that.serves.json.com/json/ | json_xs
並格式化文件中包含的JSON,您可以這樣做:
$ json_xs < file-full-of.json
要重新格式化為YAML ,有些人認為它比JSON更具人性化可讀性:
$ json_xs -t yaml < file-full-of.json
我通常只做:
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"]'
如果JSON數據在文件中:
python -mjson.tool filename.json
如果您想使用身份驗證令牌在命令行中使用curl
一次性完成所有操作:
curl -X GET -H "Authorization: Token wef4fwef54te4t5teerdfgghrtgdg53" http://testsite/api/ | python -mjson.tool
或者,使用Ruby:
echo '{ "foo": "lorem", "bar": "ipsum" }' | ruby -r json -e 'jj JSON.parse gets'
這就是我這樣做的方式:
gem install jazor
jazor --help
它縮短了代碼並完成了工作。