sveatlo
sveatlo

Reputation: 593

FOR loop in object/array

I'm creating an application using python. I make a HTTP request and get a following result:

{
    "companies": {
        "company": [
            {
                "createDt": "2014-01-18T00:00:00+01:00",
                "dbNazev": "sveatlo_s_r_o_",
                "id": "1",
                "licenseGroup": "null",
                "nazev": "Sveatlo s.r.o.",
                "show": "true",
                "stavEnum": "ESTABLISHED",
                "watchingChanges": "false"
            },
            {
                "createDt": "2014-01-20T00:00:00+01:00",
                "dbNazev": "hajocka",
                "id": "2",
                "licenseGroup": "null",
                "nazev": "HájoÄka",
                "show": "true",
                "stavEnum": "ESTABLISHED",
                "watchingChanges": "false"
            }
        ]
    }
}

Then I'm processing the data in a for loop. the problem is that the response may also look like this:

{
    "companies": {
        "company": {
            "createDt": "2014-01-18T00:00:00+01:00",
            "dbNazev": "sveatlo_s_r_o_",
            "id": "1",
            "licenseGroup": "null",
            "nazev": "Sveatlo s.r.o.",
            "show": "true",
            "stavEnum": "ESTABLISHED",
            "watchingChanges": "false"
        }
    }
}

Currently I'm checking if it is an array or not after each request like this, but I feel it's not the best way to do this. Could anybody please help me to find a better solution?

Thanks for any answer.

edit: I cannot change the server's response

Upvotes: 0

Views: 286

Answers (2)

Joel Cornett
Joel Cornett

Reputation: 24788

Normalize the information you're parsing. This will prevent you having to repeat yourself:

Say you have data that could either look like this:

some_json_data = {"companies": {"foo": 1}}

or like this:

some_json_data = {"companies": [{"foo": 1}]}

So when you parse the json data, do this:

i_expect_an_array = some_json_data['companies']
if not isinstance(i_expect_an_array, list):
    i_expect_an_array = (i_expect_an_array,)

# Now, you can process the data as you normally would

No need for two separate blocks of similar looking code.

Upvotes: 5

KiraLT
KiraLT

Reputation: 2607

Convert not list to list or tuple and then loop:

def make_list(item):
    if not isinstance(item, (list, tuple)):
        return [item]
    return list(item)

for company in make_list(data['companies']['company']):
    process_company(company)

Upvotes: 2

Related Questions