此JSON结构来自Spring Cloud服务器配置:
{
"item[0].subitem[0].key": "value1",
"item[0].subitem[1].key": "value2",
"item[1].subitem[0].key": "value3",
"item[1].subitem[1].key": "value4"
}
我有一个Flask应用程序,它将使用该格式,但是我需要将其转换为这种格式以进行进一步处理:
{
"item": [
{
"subitem": [
{
"key": "value1"
},
{
"key": "value1"
}
]
},
{
"subitem": [
{
"key": "value1"
},
{
"key": "value1"
}
]
}
]
}
答案 0 :(得分:1)
下面的代码显示了一种通用解决方案,其中包括比您的要求更多的测试用例:
import re
j = {
"item[0].subitem[0].key": "value1",
"item[0].subitem[1].key": "value2",
"item[1].subitem[0].key": "value3",
"item[1].subitem[1].key": "value4",
"item2[0].subitem[0]": "value5",
"item2[0].subitem[1]": "value6",
"item2[1][0].key1": "value7",
"item2[1][1].key2": "value8"
}
d = {}
for key, value in j.items():
s = d
tokens = re.findall(r'\w+', key)
for count, (index, next_token) in enumerate(zip(tokens, tokens[1:] + [value]), 1):
value = next_token if count == len(tokens) else [] if next_token.isdigit() else {}
if isinstance(s, list):
index = int(index)
while index >= len(s):
s.append(value)
elif index not in s:
s[index] = value
s = s[index]
d
变为:
{'item': [{'subitem': [{'key': 'value1'}, {'key': 'value2'}]},
{'subitem': [{'key': 'value3'}, {'key': 'value4'}]}],
'item2': [{'subitem': ['value5', 'value6']},
[{'key1': 'value7'}, {'key2': 'value8'}]]}
答案 1 :(得分:1)
答案 2 :(得分:0)
我解释了为什么我不想在OP问题的评论中提供完整的解决方案。这应该足够提示:
def main():
input = {
"item[0].subitem[0].key": "value1",
"item[0].subitem[1].key": "value2",
"item[1].subitem[0].key": "value3",
"item[1].subitem[1].key": "value4",
}
items = list(input.items())
random.shuffle(items)
shuffled = dict(items)
result = normalize_keys(unflatten(shuffled))
print(json.dumps(result, indent=2))
结果:
{
"item": [
{
"subitem": [
{
"key": "value1"
},
{
"key": "value2"
}
]
},
{
"subitem": [
{
"key": "value3"
},
{
"key": "value4"
}
]
}
]
}