gpt4 book ai didi

python - pretty-print JSON 转储

转载 作者:太空狗 更新时间:2023-10-29 16:57:00 26 4
gpt4 key购买 nike

我使用这段代码将 dict 漂亮地打印成 JSON:

import json
d = {'a': 'blah', 'b': 'foo', 'c': [1,2,3]}
print json.dumps(d, indent = 2, separators=(',', ': '))

输出:

{
"a": "blah",
"c": [
1,
2,
3
],
"b": "foo"
}

这有点太多(每个列表元素换行!)。

我应该使用哪种语法来实现:

{
"a": "blah",
"c": [1, 2, 3],
"b": "foo"
}

代替?

最佳答案

我最终使用了 jsbeautifier :

import jsbeautifier
opts = jsbeautifier.default_options()
opts.indent_size = 2
jsbeautifier.beautify(json.dumps(d), opts)

输出:

{
"a": "blah",
"c": [1, 2, 3],
"b": "foo"
}

关于python - pretty-print JSON 转储,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21866774/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com