gpt4 book ai didi

python - 重命名 JSON 键名

转载 作者:行者123 更新时间:2023-12-04 10:15:47 33 4
gpt4 key购买 nike

我收到一个这样的 JSON 对象:

{
"Question Communicating": "Natural language",
"interpretation_type": "recognition",
"output1": "test",
"Question Learning": "Reinforcement",
"output2": "test2",
"output3": "something"
}

我的问题是,是否可以重命名 key 名称: 'outputX''output' .
不知道多少次 'outputX'将在 JSON 中,但我需要将所有输出重命名为 'output' .
所以最终会是这样:
{
"Question Communicating": "Natural language",
"interpretation_type": "recognition",
"output": "test",
"Question Learning": "Reinforcement",
"output": "test2",
"output": "something"
}

最佳答案

不建议尝试在 JSON 对象中使用重复键。您可以看到序列化和反序列化重复键时出现的问题,或者尝试将它们强制放入字典中。不保留重复键。

>>> from json import dumps, loads
>>> json = '{"a": "x", "a": "y"}'
>>> loads(json)
{'a': 'y'}
>>> json = {'a': 'x', 'a': 'y'}
>>> dumps(json)
'{"a": "y"}'
>>> json = {'a': 'x', 'a': 'y'}
>>> json
{'a': 'y'}

相反,您可以尝试将所有以 "output" 开头的键分组。进入列表 ["test", "test2", "something"] .
from json import dumps

d = {
"Question Communicating": "Natural language",
"interpretation_type": "recognition",
"output1": "test",
"Question Learning": "Reinforcement",
"output2": "test2",
"output3": "something"
}

result = {}
for k, v in d.items():
if k.startswith("output"):
result.setdefault("output", []).append(v)
else:
result[k] = v

print(dumps(result, indent=4))

输出 JSON:
{
"Question Communicating": "Natural language",
"interpretation_type": "recognition",
"output": [
"test",
"test2",
"something"
],
"Question Learning": "Reinforcement"
}

关于python - 重命名 JSON 键名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61063410/

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