pydevcode
pydevcode

Reputation: 15

Split array in json into mutiple objects in Python

I have a JSON object which contains array fields. Now I want o extract the array and split it into multiple objects.

JSON object:-

{'catalog_num': 5,
    'data_array': ['16.1', 
                   '76.1', 
                   '14.1', 
                   '14.1'
                  ]
}

Now I want the split this json array into multiple objects

   {'catalog_num': 5,
    'data_id': '16.1'},

 {'catalog_num': 5,
    'data_id': '76.1'},

   {'catalog_num': 5,
    'data_id': '14.1'},

   {'catalog_num': 5,
    'data_id': '14.1'},

Upvotes: 1

Views: 2024

Answers (2)

Msv
Msv

Reputation: 1371

please let me know if you have any other requirements

data = {'catalog_num': 5,
    'data_array': ['16.1', 
                   '76.1', 
                   '14.1', 
                   '14.1'
                  ]
}

objects_list = []

for data in data["data_array"]:
    object = {
       'catalog_num': data['catalog_num'],
       'data_id': data
    }
    objects_list.append(object)

print(objects_list)

Upvotes: 0

exilour
exilour

Reputation: 556

In addition to @Sridhar's answer, you can do this with list comprehension with less code like this

data = {'catalog_num': 5,
        'data_array': ['16.1',
                       '76.1',
                       '14.1',
                       '14.1'
                       ]
        }


result = [{
    'catalog_num': data['catalog_num'],
    'data_id': data_id,
} for data_id in data['data_array']]

Upvotes: 2

Related Questions