0

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 (....,"[email protected]",....). 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:

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:

[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]

I need:

boo
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
boo
[email protected]
[email protected]
2
  • 2
    if emails := item['contacts']['emailAddresses']: for email in emails ... else: print("boo") Commented Aug 4, 2022 at 18:05
  • 1
    item['contacts']['emailAddresses'] is the list, so for email in item['contacts']['emailAddresses'] will give you each item in the list ... if the items are strings then if email == [] doesn't make sense. Your if statement should be outside the for loop, instead of inside it, and should check that item['contacts']['emailAddresses'] is not an empty list. @Olvin Roght gives a nice compact version of that above Commented Aug 4, 2022 at 18:13

1 Answer 1

2

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")
Sign up to request clarification or add additional context in comments.

Comments

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.