是否有(Unix)shell脚本将JSON格式化为可读格式?
基本上,我希望它转换以下内容:
{ "foo": "lorem", "bar": "ipsum" }
…变成这样:
{
"foo": "lorem",
"bar": "ipsum"
}
是否有(Unix)shell脚本将JSON格式化为可读格式?
基本上,我希望它转换以下内容:
{ "foo": "lorem", "bar": "ipsum" }
…变成这样:
{
"foo": "lorem",
"bar": "ipsum"
}
当前回答
你可以用西德尔。
Xidel是一个命令行工具,可以使用CSS、XPath 3.0、XQuery 3.0、JSONiq或模式模板从HTML/XML页面或JSON API下载和提取数据。它还可以创建新的或转换的XML/HTML/JSON文档。
默认情况下,Xidel漂亮打印:
$ xidel -se '$json' <<< '{"foo":"lorem","bar":"ipsum"}'
{
"foo": "lorem",
"bar": "ipsum"
}
or:
$ echo '{"foo":"lorem","bar":"ipsum"}' | xidel -se '$json'
{
"foo": "lorem",
"bar": "ipsum"
}
其他回答
$ sudo apt-get install edit-json
$ prettify_json myfile.json
我的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/.我认为这一个解析器比其他许多解析器更能容错。
多亏了J.F.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))
对于Node.js,您也可以使用“util”模块。它使用语法高亮显示、智能缩进、从键中删除引号,并使输出尽可能漂亮。
cat file.json | node -e "process.stdin.pipe(new require('stream').Writable({write: chunk => {console.log(require('util').inspect(JSON.parse(chunk), {depth: null, colors: true}))}}))"
一个用于漂亮json打印的简单bash脚本
json_prety.sh
#/bin/bash
grep -Eo '"[^"]*" *(: *([0-9]*|"[^"]*")[^{}\["]*|,)?|[^"\]\[\}\{]*|\{|\},?|\[|\],?|[0-9 ]*,?' | awk '{if ($0 ~ /^[}\]]/ ) offset-=4; printf "%*c%s\n", offset, " ", $0; if ($0 ~ /^[{\[]/) offset+=4}'
例子:
cat file.json | json_pretty.sh