Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Identifying empty list in JSON data in Python

I have a json data set I’m trying to insert into a database. To do so, I need placeholders "" for non-existent data. In the example below, if there’s no email address, I need the insert statement to be (….,"boo",….) instead of (….,"me@mail.com",….). I have tried checking for list length, using not, email == [], etc. Every way I know how or have Googled, and none are working.

Example data:

{
    "data": [
        {
            "campsites": {
                ...
            },
            "contacts": {
                "emailAddresses": [],
                "phoneNumbers": []
            },
...

My code for this particular section:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

results = response.json()['data']
for item in results:
    for email in item['contacts']['emailAddresses']:
        if email == []:
            print("boo")
        else:
            print(email['emailAddress'])

The if statement (regardless of how I’ve tried so far), does not execute, and I get a printed list of only the email addresses if they exist:

GRSM_Smokies_Information@nps.gov
CATO_superintendent@nps.gov
dyanna.threeirons@crow-nsn.gov
ozar_campground_operation@nps.gov
orpi_information@nps.gov
ozar_campground_operations@nps.gov
biso_information@nps.gov
chis_information@nps.gov
info@antelopepointmarina.com

I need:

boo
GRSM_Smokies_Information@nps.gov
CATO_superintendent@nps.gov
dyanna.threeirons@crow-nsn.gov
ozar_campground_operation@nps.gov
orpi_information@nps.gov
ozar_campground_operations@nps.gov
biso_information@nps.gov
boo
chis_information@nps.gov
info@antelopepointmarina.com

>Solution :

If the list of "emailAddresses" is empty, the for loop doesn’t get executed. Accordingly print("boo") neither.

You need to check the list first, before iterate through the list:

results = response.json()["data"]
for item in results:
    emails = item["contacts"]["emailAddresses"]
    if emails:
        for email in emails:
            print(email)
    else:
        print("boo")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading