Home > OS >  How to handle when API Response returns either list or dict in Python?
How to handle when API Response returns either list or dict in Python?

Time:10-16

I am parsing an API in python using responseJson = json.loads(response.text)

The API response is somewhat like this:

  1. When having single entry in books
{
    "name": "A",
    "books": {
        "bookname": "BookA"
    }
}

or 2. When having multiple entries in books

{
    "name": "A",
    "books": [
        {
            "bookname": "BookA"
        },
        {
            "bookname": "BookB"
        }
    ]
}

Currenty I am using:

if type(responseJson['books']) is dict:
   bookName.append(responseJson['books']['bookname'])
    # do a lot more stuff
else:
    for val in responseJson['books']:
        bookName.append(val['bookname'])
            # do a lot more stuff

Since the code (# do a lot more stuff) is a bit complex, I was looking to find an optimized way to do this instead of relying on type().

Any suggestions on how to improve code quality here?

CodePudding user response:

I would use isinstance instead of type but instead of having to different branches that do a bunch of stuff I would only look for the dictionaries and if found wrap place it inside of a list and then you only need one branch that does stuff.

for example:

books = response.json['books']
if isinstance(books, dict):
    books = [books]
for val in books:
    bookName.append(val['bookname'])
    #  do alot more stuff
  • Related