1

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'},
4
  • you mean different dict variables according to elements in data_id? Commented Apr 12, 2021 at 4:45
  • That's not a JSON object, that's a Python dictionary. Commented Apr 12, 2021 at 5:10
  • Consider the answers if they solve your problem and upvote them Commented Apr 12, 2021 at 5:14
  • is not a JSON file, JSON requires double quotes. Commented Apr 12, 2021 at 5:29

2 Answers 2

2

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

3 Comments

maybe it's too advanced to talk about list comprehensions for newbies. Just an opinion :)
That is why I added it as an addition to your answer, your's is descriptive. He should know what options exist, I think.
Yeah nice job. see ya
0

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)

Comments

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.