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

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

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

…变成这样:

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

当前回答

我提出了这个解决方案:https://calbertts.medium.com/unix-pipelines-with-curl-requests-and-serverless-functions-e21117ae4c65

# this in your bash profile
jsonprettify() {
  curl -Ss -X POST -H "Content-Type: text/plain" --data-binary @- https://jsonprettify.vercel.app/api/server?indent=$@
}
echo '{"prop": true, "key": [1,2]}' | jsonprettify 4
# {
#     "prop": true,
#     "key": [
#         1,
#         2
#     ]
# }

不需要安装任何东西,如果您安装了internet连接和cURL,则可以使用此功能。

如果您在另一个无法安装任何东西的主机上,这将是该问题的完美解决方案。

其他回答

有TidyJSON。

它是C#,所以也许你可以让它用Mono编译,并使用*nix。但没有保证,抱歉。

我通常只做:

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

这里有一个比Json的pretify命令更好的Ruby解决方案。gem colorful_json相当不错。

gem install colorful_json
echo '{"foo": "lorem", "bar": "ipsum"}' | cjson
{
  "foo": "lorem",
  "bar": "ipsum"
}

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

JSONLint在GitHub上有一个开源实现,可以在命令行上使用,也可以包含在Node.js项目中。

npm install jsonlint -g

然后

jsonlint -p myfile.json

or

curl -s "http://api.twitter.com/1/users/show/user.json" | jsonlint | less