0

I am new to python and I would like to understand how to access an array in a json object without referring to its name.

The given json object has the below structure

import json

input_json = {
    "records": [
        {
            "values": {
                "col1": "1"
            },
            "no": 1,
        },
        {
            "values": {
                "col1": "2"
            },
            "no": 2,
        }
    ],
    "number_of_records": 2
}

myVar = json.load(input_json)
for i in myVar['records']:            # How do I replace this line?
      print  i['values']['col1']

I need to loop through the objects inside the 'records' array. How can I fetch the array without using myVar['records']?

Note that the code cannot depend on the order of the json attributes too. The only thing guaranteed is that the json string would have only one array in it.

1 Answer 1

1
input_json = {
    "records": [
        {
            "values": {
                "col1": "1"
            },
            "no": 1,
        },
        {
            "values": {
                "col1": "2"
            },
            "no": 2,
        }
    ],
    "number_of_records": 2
}

for anything in input_json:
    if isinstance(input_json[anything], list):
        for values in input_json[anything]:
            print(values['values']['col1'])

You can also further nest the for loop if you don't know the 'values' and 'col1' names.

Sign up to request clarification or add additional context in comments.

3 Comments

Isn't the code still relying on the attribute name 'records'? Did I misunderstand it?
it is not relying on 'records' but records. which you can change it to anything
That's amazing. So basically we are looping through the input json and checking if there is any list inside it. If so, we fetch the 'values' objects from it and proceed. Is that right?

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.