Leo Torres
Leo Torres

Reputation: 690

Check if a child node exists 2 levels deep

I need to check if a json node exists.

ownerid = jsonData[0]['owner']['id']

If this exists I dont have an issue. There are times when owner node is not there so I have this and it works

if("owner" in jdata): #jdata is of type string
     ownerid = jsonData[0]['owner']['id']
else:
     ownerid = jsonData[0]['owner']['id']

This will work when owner does not exists.

My issue is when owner node exists but the 'id' node does not because the owner condition is met and id does not exists so my process fails.

Here is the question how do I check for that specific node inside owner.

I can not use

if("id" in jdata) #jdata is of type string

The search word "id" is very common in file. I will get hits but does not necessarily mean id exists inside owner node. How can I check for id with a specific node so I can determine what to do next

FYI... I tried

if("id" in jsonData[0]['owner']) #jsonData of type list

got an error

argument of type 'NoneType' is not iterable

Upvotes: 0

Views: 233

Answers (1)

flgang
flgang

Reputation: 114

use dict.get() avoid NoneType error

ownerid = jsonData[0].get('owner',{}).get('id')
if ownerid:
    print('ownerid exist')
else:
    print('ownerid not exist')

Upvotes: 1

Related Questions