Home > Enterprise >  converting list of lists to json in python
converting list of lists to json in python

Time:08-20

i have list of lists but the sublists are huge around 10.000 elements

[['x1', 'y1', 'z1', 'w2'], ['x2', 'y2', 'z2', 'p3'], ['r3', 't3', 'n3']]

and i want to convert each sublist to JSON Where #Number is replaced by the elements

{
  "SchedTime": "string",
  "Messages": [
    {
      "Number": "#Number",
      "Text": msg
    },
   {
      "Number": "#Number",
      "Text": msg
    }
  ],
  "keyID": "string",
  "ClientId": "string"
}

for example the first sublist above like this

{
  "SchedTime": "string",
  "Messages": [
    {
      "Number": "x1",
      "Text": msg
    },
   {
      "Number": "y1",
      "Text": msg
    },
  {
      "Number": "z1",
      "Text": msg
    },
  {
      "Number": "w2",
      "Text": msg
    }
  ],
  "keyID": "string",
  "ClientId": "string"
}

CodePudding user response:

Not sure what you tryna do but I guess something like this

l = [['x1', 'y1', 'z1', 'w2'], ['x2', 'y2', 'z2', 'p3'], ['r3', 't3', 'n3']]

nl = []
msg = 'something'

for e in l:
    nl.append({
        'SchedTime': 'string',
        'Messages': [ {'Number': x, 'Text': msg} for x in e],
        'keyID': 'string',
        'ClientId': 'string'
        })

print(nl)
  • Related