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

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

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

…变成这样:

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

当前回答

您可以使用Pretier来执行此操作。

npx更漂亮的<JSON文件>应该在给定文件中打印一个经过修饰的JSON版本,而npx更美丽的--write<JSON文件>将用经过修饰的JSON覆盖给定的JSON文件。

其他回答

$ sudo apt-get install edit-json
$ prettify_json myfile.json

当您的系统上安装了节点时,以下工作正常。

echo '{"test":1,"test2":2}' | npx json

{
  "test": 1,
  "test2": 2
}

我知道最初的帖子要求提供一个shell脚本,但有太多有用和不相关的答案,可能对原作者没有帮助。添加到不相关的内容:)

顺便说一下,我无法使用任何命令行工具。

如果有人想要简单的JSON JavaScript代码,他们可以这样做:

JSON.stringfy(JSON.parse(str), null, 4)

http://www.geospaces.org/geoweb/Wiki.jsp?page=JSON%20Utilities%20Demos

这里是JavaScript代码,它不仅美化了JSON,还按其属性或属性和级别对其进行排序。

如果输入是

{ "c": 1, "a": {"b1": 2, "a1":1 }, "b": 1},

它要么打印(将所有对象分组在一起):

{
     "b": 1,
     "c": 1,
     "a": {
          "a1": 1,
          "b1": 2
     }
}

OR(仅按键排序):

{
 "a": {
      "a1": 1,
      "b1": 2
 },
 "b": 1,
 "c": 1
}

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