是否有(Unix)Shell 脚本以易于理解的格式格式化 JSON?
基本上,我希望它可以转换以下内容:
{ "foo": "lorem", "bar": "ipsum" }
... 变成这样:
{
"foo": "lorem",
"bar": "ipsum"
}
使用 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
使用非常简单,效果很好!它可以处理非常大的 JSON 结构,包括流。您可以在此处找到他们的教程。
用法示例:
$ 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"
}
的。是身份过滤器。
我使用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');
从带有 Node.js 的 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,Dev 控制台,“网络” 选项卡,全部导出为 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
这个工具是我目前的热情项目,因此,如果您有任何功能要求,我很有可能会解决。
我通常只是这样做:
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
感谢 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))
如果使用 npm 和 Node.js,则可以执行npm install -g json
,然后通过json
传递命令。执行json -h
以获取所有选项。它还可以提取特定字段,并使用-i
为输出着色。
curl -s http://search.twitter.com/search.json?q=node.js | json
对于 Perl,请使用 CPAN 模块JSON::XS
。它安装了命令行工具json_xs
。
验证:
json_xs -t null < myfile.json
将 JSON 文件src.json
为pretty.json
:
< src.json json_xs > pretty.json
如果您没有json_xs
,请尝试json_pp
。 “pp” 表示 “纯 perl” –该工具仅在 Perl 中实现,没有绑定到外部 C 库(XS 代表 Perl 的 “扩展系统”)。
在 * 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)
将此文件放入您的 PATH 文件中(我在AnC的回答后命名为 mine“prettyJSON”),然后对其进行chmod +x
调试 ,您就可以开始了。