1

Can you advise on a list of actions/commands I need to do in order to fix the below JSON using Python. Current:

{
   "artifacts":[ 
     [ 
         "path: scheduler-task",
         "version: 0.28.2",
         "type: helm",
         "chart: scheduler-task",
         "repository: amd-core-test-helm-release"
     ]
   ]
}

Expected:

{ 
   "artifacts":[ 
     {
         "path": "scheduler-task",
         "version": "0.28.2",
         "type": "helm",
         "chart": "scheduler-task",
         "repository": "amd-core-test-helm-release"
     }
   ]
}
1
  • what encoded the original string, i'm interested in the library that did that Commented Nov 24, 2019 at 4:59

1 Answer 1

5

The idea is to remap each string "foo: bar" into a dictionary with key as "foo" and value "bar". The snippet below converts the data in the required format.

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))

Output:

{
  "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"
    }
  ]
}
Sign up to request clarification or add additional context in comments.

9 Comments

Do you happen to know what encoded his original string? I'm wondering what was used it for encoding, as there might be an easier way to decode it with a library. +1 great answer
you could use split(": ") with space to remove this space from value.
@oppressionslayer, indeed that'll be helpful. If OP provides the source, we can write a generalized routine for it or use some in-built function.
@Kirk, true that. This however solves the current problem, so can be left for the OP to figure out I guess.
@ShubhamSharma Agreed! Just pointing it out upfront in case the OP's problem is a bit more complex than the example given.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.