[英]JSON pretty print multiple lines
在python中做這樣的事情:
import json
with open('msgs.json', 'r') as json_file:
for row in json_file:
data = json.loads(row)
print(json.dumps(data, sort_keys=True, indent=2, separators=(',', ': ')))
jq
可以做到這一點以及更多,這是我使用的,但對你來說可能有點過頭了。 你可以在這里找到它。
cat yourfile.json | jq '.'
應該做的伎倆
myjson.py - 一個經過修改的 json 工具,支持多個 JSON 消息:
#!/usr/bin/python
"""myjson.py: Command-line tool to validate and pretty-print JSON
Usage::
1) $ echo '{"json":"obj"}' | python myjson.py
{
"json": "obj"
}
2) $ echo '{ 1.2:3.4}' | python myjson.py
Expecting property name enclosed in double quotes: line 1 column 2 (char 2)
3) printing a file with multiple lines where each line is a JSON message:
e.g. msgs.json:
[1,,{"6":7,"4":5}]
[2,{"6":7,"4":5}]
python myjson.py msgs.json
[
1,
{
"4": 5,
"6": 7
}
]
[
2,
{
"4": 5,
"6": 7
}
]
"""
import sys
import json
def main():
data = []
if len(sys.argv) == 1:
infile = sys.stdin
outfile = sys.stdout
elif len(sys.argv) == 2:
infile = open(sys.argv[1], 'rb')
outfile = sys.stdout
elif len(sys.argv) == 3:
infile = open(sys.argv[1], 'rb')
outfile = open(sys.argv[2], 'wb')
else:
raise SystemExit(sys.argv[0] + " [infile [outfile]]")
with infile:
try:
for line in infile:
data.append(json.loads(line))
except ValueError, e:
raise SystemExit(e)
with outfile:
for d in data:
json.dump(d, outfile, sort_keys=True,
indent=4, separators=(',', ': '))
outfile.write('\n')
if __name__ == '__main__':
main()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.