[英]how to format json dumps
I got json dumps like this: 我有这样的json转储:
"aaa": {
"bbb": {
"ccc": {
"ddd": "string1",
"eee": "string2"
}
},
"kkk": "string3"
}
And I'd like to format it this way: enclose every key-value pair (separated by :
) with {}
and then replace :
with ,
. 而且我想这样格式化
:
用{}
括住每个键值对(用:
分隔),然后用,
替换:
。
I know that I can use re.sub()
to replace string patterns, but regular expression does not work with overlapping patterns, so I can match, for example, "ddd": "string1"
but not "ccc": {...}
at the same time . 我知道我可以使用
re.sub()
替换字符串模式,但是正则表达式不适用于重叠模式,因此我可以匹配例如"ddd": "string1"
而不是"ccc": {...}
在同一时间 。
For the above json string, I'd like to get: 对于上述json字符串,我想获取:
{"aaa", {
{"bbb", {
{"ccc", {
{"ddd", "string1"},
{"eee", "string2"}
}}
}},
{"kkk", "string3"}
}}
Here's a hack which converts everything to lists and then changes square brackets to curly ones. 这是一种将所有内容转换为列表,然后将方括号更改为大括号的hack。 If your strings might contain square brackets that'll be a problem.
如果您的字符串中可能包含方括号,那将是一个问题。
import json
inp = """
{
"aaa": {
"bbb": {
"ccc": {
"ddd": "string1",
"eee": "string2"
}
},
"kkk": "string3"
}
}
"""
inp = json.loads(inp)
def items(d):
if isinstance(d, dict):
return [(k, items(v)) for k, v in d.items()]
return d
inp = items(inp)
print(json.dumps(inp, indent=2).replace("[", "{").replace("]", "}"))
Output: 输出:
{
{
"aaa",
{
{
"bbb",
{
{
"ccc",
{
{
"ddd",
"string1"
},
{
"eee",
"string2"
}
}
}
}
},
{
"kkk",
"string3"
}
}
}
}
Note that you are treating dictionary keys as ordered when they aren't, so I made it more explicit with lists. 请注意,您在不按顺序处理字典键时将其按顺序处理,因此我使用列表使其更加明确。
If it were me, I wouldn't dump to JSON in the first place, I'd serialize the native python data structure straight to C++ initializer list syntax: 如果是我,那么我一开始就不会转储到JSON,而是直接将本机python数据结构序列化为C ++初始化列表语法:
myobj = {
"aaa": [
{ "bbb": {
"ccc": [
{"ddd": "string1"},
{"eee": "string2"}
]
}},
{ "kkk": "string3" }
]
}
def pyToCpp(value, key=None):
if key:
return '{{ "{}", {} }}'.format(key, pyToCpp(value))
if type(value) == dict:
for k, v in value.items():
return pyToCpp(v, k)
elif type(value) == list:
l = [pyToCpp(v) for v in value]
return '{{ {} }}'.format(", ".join(l))
else:
return '"{}"'.format(value)
y = pyToCpp(myobj)
print(y)
Output: 输出:
{ "aaa", { { "bbb", { "ccc", { { "ddd", "string1" }, { "eee", "string2" } } } }, { "kkk", "string3" } } }
Run it here: https://repl.it/repls/OddFrontUsers 在这里运行: https : //repl.it/repls/OddFrontUsers
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.