Home > Blockchain >  how to create dynamic json object with length?
how to create dynamic json object with length?

Time:10-29

{
  "update": {
    "labels": [
      {
        "add": "Demo"
      },
      {
        "add": "BRANCH_NAME"
      },
      {
        "add": "BRANCH_NAME_BUILD_NUMBER"
      },
      {
        "add": "Dummy"
      },............
    ]
  }
}

How to create dynamically json object for curl --data parameter.

Challenges:

  1. I have tuple as data= ("Demo","BRANCH_NAME","BRANCH_NAME_BUILD_NUMBER","Dummy")
  2. If i have n numbers strings in data parameter then how to create dynamic json object for n number of strings.
  3. Need help for if in tuple 4 values are then in mentioned json under labels array 4 objects create.

CodePudding user response:

if you have your data in a strucute like:

data = ("Demo","BRANCH_NAME","BRANCH_NAME_BUILD_NUMBER","Dummy")
# this also work for any number of strings you will have inside, like:
# data = ("Demo","BRANCH_NAME","BRANCH_NAME_BUILD_NUMBER","Dummy","foo","bar","baz")
# data = ("foo")

you can just do:

labels = [{"add": i} for i in data]

out_json = {
    "update": {
        "labels": labels
    }
}
# formatted for better readability
>>> labels
[
    {'add': 'Demo'}, 
    {'add': 'BRANCH_NAME'}, 
    {'add': 'BRANCH_NAME_BUILD_NUMBER'}, 
    {'add': 'Dummy'}
]
>>> out_json
{
    'update': {
        'labels': [
                {'add': 'Demo'}, 
                {'add': 'BRANCH_NAME'}, 
                {'add': 'BRANCH_NAME_BUILD_NUMBER'}, 
                {'add': 'Dummy'}
            ]
    }
}
  • Related