是否有(Unix)shell脚本将JSON格式化为可读格式?

基本上,我希望它转换以下内容:

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

…变成这样:

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

当前回答

根据我的经验,雅杰很好。我使用它的json_reformat命令在vim中漂亮地打印.json文件,方法是在我的.vimrc中放置以下行:

autocmd FileType json setlocal equalprg=json_reformat

其他回答

我正在使用httpie

$ pip install httpie

你可以这样使用

 $ http PUT localhost:8001/api/v1/ports/my 
 HTTP/1.1 200 OK
 Connection: keep-alive
 Content-Length: 93
 Content-Type: application/json
 Date: Fri, 06 Mar 2015 02:46:41 GMT
 Server: nginx/1.4.6 (Ubuntu)
 X-Powered-By: HHVM/3.5.1

 {
     "data": [], 
     "message": "Failed to manage ports in 'my'. Request body is empty", 
     "success": false
 }

我的JSON文件没有被这些方法解析。

我的问题类似于帖子“Google数据源JSON无效吗?”?。

那篇帖子的答案帮助我找到了解决方案。

它被认为是没有字符串键的无效JSON。

{id:'name',label:'Name',type:'string'}

必须是:

{"id": "name", "label": "Name", "type": "string"}

此链接对一些不同的JSON解析器进行了很好的全面比较:http://deron.meranda.us/python/comparing_json_modules/basic

这让我http://deron.meranda.us/python/demjson/.我认为这一个解析器比其他许多解析器更能容错。

如果使用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_x,请尝试json_pp。“pp”代表“纯perl”——该工具仅在perl中实现,没有绑定到外部C库(XS代表perl的“扩展系统”)。

看看Jazor。这是一个用Ruby编写的简单命令行JSON解析器。

gem install jazor
jazor --help