python - 使用 python 修复 JSON 结构

标签 python json

为了使用 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/

相关文章:

javascript - 如何在 laravel TableView Blade 中显示 JSON 中的指定对象值

iphone - 从 JSON 中过滤 NSArray?

python - AES key 的内容重要吗?

python - 使用迭代将旧字典中的值提取到新字典中

Python提示用户有回声和密码没有回声

json - Dart/flutter : build_value vs json_serializable

python - 将 asyncio.Queue 用于生产者-消费者流程

python - 将 Django 与 Apache、mod-wsgi 和 mod-wsgi_httpd 结合使用

javascript - 从 Firebase 检索数据未在控制台中正确显示

c# - 使用 JSON.Net 自定义 JSON 到 XML 的转换