在 JSON 输出中,强制每个左花括号出现在一个新的单独行中 [英] In JSON output, force every opening curly brace to appear in a new separate line
问题描述
在我的代码中使用 json.dumps(some_dict,indent=4,sort_keys=True)
:
我得到了这样的东西:
{
"a": {
"x":1,
"y":2
},
"b": {
"z":3,
"w":4
}
}
但我想要这样的东西:
{
"a":
{
"x":1,
"y":2
},
"b":
{
"z":3,
"w":4
}
}
如何强制每个左花括号出现在新的单独行的开头?
How can I force each opening curly brace to appear at the beginning of a new separate line?
我是否必须编写自己的 JSON 序列化程序,或者在调用 json.dumps
时是否可以使用特殊参数?
Do I have to write my own JSON serializer, or is there a special argument that I can use when calling json.dumps
?
推荐答案
您可以对结果使用正则表达式替换.
You can use a regular expression replacement on the result.
better_json = re.sub(r'^((\s*)".*?":)\s*([\[{])', r'\1\n\2\3', json, flags=re.MULTILINE)
第一个捕获组匹配属性名称之后的 :
之前的所有内容,第二个捕获组匹配属性名称前的空格,第三个捕获组捕获 {
或 [
在对象或数组之前.然后在换行符之后复制空格,以便缩进正确匹配.
The first capture group matches everything up to the :
after the property name, the second capture group matches the whitespace before the property name, and the third capture group captures the {
or [
before the object or array. The whitespace is then copied after the newline, so that the indentation will match properly.
这篇关于在 JSON 输出中,强制每个左花括号出现在一个新的单独行中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!