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

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

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

…变成这样:

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

当前回答

对于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的“扩展系统”)。

其他回答

我正在使用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/.我认为这一个解析器比其他许多解析器更能容错。

如果你安装了Node.js,你可以用一行代码自己创建一个Node.js。创建一个漂亮的文件:

>vim漂亮

#!/usr/bin/env node

console.log(JSON.stringify(JSON.parse(process.argv[2]), null, 2));

添加执行权限:

>chmod+x漂亮> ./漂亮的“{”foo“:”lorem“,”bar“:”ipsum“}”

或者如果JSON在文件中:

#!/usr/bin/env node

console.log(JSON.stringify(require("./" + process.argv[2]), null, 2));

> ./漂亮的文件.json

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

工具ydump是一个JSON漂亮的打印机:

$ ydump my_data.json
{
  "foo": "lorem",
  "bar": "ipsum"
}

或者可以通过管道输入JSON:

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

这可能是除了使用jq工具之外最短的解决方案。

该工具是OCaml的yojson库的一部分,并在此处进行了说明。

在Debian及其衍生产品上,libyojson-ocml-dev包包含此工具。或者,可以通过OPAM安装yojson。