1

I am trying to select all the sections that have a "photo" within "employee" which is found within "employees". If they don't have a "photo", I do not want to select this section. Is there a way to do this? I am using SQL in SNOWFLAKE.

For example, I have this JSON:

 {
      "employees": {
        "employee": [
          {
            "id": "1",
            "firstName": "Tom",
            "lastName": "Cruise",
            "photo": "https://pbs.twimg.com/profile_images/735509975649378305/B81JwLT7.jpg"
          },
          {
            "id": "2",
            "firstName": "Maria",
            "lastName": "Sharapova"
          },
          {
            "id": "3",
            "firstName": "James",
            "lastName": "Bond"
          }
        ]
      }
    }

Since the last two don't have "PHOTO" I do not want this return. So for the above, it should only return:

      {
        "id": "1",
        "firstName": "Tom",
        "lastName": "Cruise",
        "photo": "https://pbs.twimg.com/profile_images/735509975649378305/B81JwLT7.jpg"
      }

2 Answers 2

1
SELECT e AS json
FROM data_table t,
LATERAL FLATTEN(input=>t.json:employees:employee) e,
WHERE e.value:photo IS NOT NULL;
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you! What if I have several objects within "Photo"? Will this method work?
@user3461502 the criteria you stated was "include it if it has a photo", thus if "it has many photo's" is still worthy of including (aka instead of an object {} photo is an array []) then this still will be good when not null? unless I have missed something?
1

YOu may consider option 4. For a more dynamic way to achieve similar results, where the position of the elements is not deterministic, Lateral Flatten with unpivot function can be handy, in the below article: https://community.snowflake.com/s/article/Dynamically-extracting-JSON-using-LATERAL-FLATTEN

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.