为了使用 Python 修复以下 JSON,您能否建议我需要执行的操作/命令列表。 当前:
{
"artifacts":[
[
"path: scheduler-task",
"version: 0.28.2",
"type: helm",
"chart: scheduler-task",
"repository: amd-core-test-helm-release"
]
]
}
预期:
{
"artifacts":[
{
"path": "scheduler-task",
"version": "0.28.2",
"type": "helm",
"chart": "scheduler-task",
"repository": "amd-core-test-helm-release"
}
]
}
最佳答案
想法是将每个字符串“foo: bar”重新映射到一个字典中,键为“foo”,值为“bar”。下面的代码片段将数据转换为所需格式。
import json
data = {
"artifacts": [
[
"path: scheduler-task",
"version: 0.28.2",
"type: helm",
"chart: scheduler-task",
"repository: amd-core-test-helm-release"
],
[
"path: ordernotification-notifycustomer",
"version: 0.29.5",
"type: helm",
"chart: ordernotification-notifycustomer",
"repository: amd-core-test-helm-release"
]
]
}
for i in range(len(data["artifacts"])):
item_dict = {}
for item in data["artifacts"][i]:
key, value = item.split(": ")
item_dict[key] = value
data["artifacts"][i] = item_dict
print(json.dumps(data))
输出:
{
"artifacts": [
{
"path": "scheduler-task",
"version": "0.28.2",
"type": "helm",
"chart": "scheduler-task",
"repository": "amd-core-test-helm-release"
},
{
"path": "ordernotification-notifycustomer",
"version": "0.29.5",
"type": "helm",
"chart": "ordernotification-notifycustomer",
"repository": "amd-core-test-helm-release"
}
]
}
关于python - 使用 python 修复 JSON 结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59014746/