3

I'm flattening a JSON data in snowflake using the Lateral Flatten.

I have the JSON data as follows:

{
   "Fruits": [
    {
      "Apple_Type" : Type_A,
      "Banana_Type": Type_B
    },
    {
      "Apple_Type" : Type_A2,
      "Banana_Type": Type_B3
    }
  ]
}

I used the following query to get the flattened data

SELECT  v.value:Apple_Type,
        v.value:Banana_Type
FROM Table1, LATERAL FLATTEN(input => Fruits) v

My Result:

--------------------------------
| Apple_Type    |  Banana_Type |
--------------------------------
| Type_A        |    Type_B   |
| Type_A2       |    Type_B3   |
--------------------------------

How do I get the index of the data. I want the table as follows

----------------------------------------------
| Apple_Type    |  Banana_Type |    Index    |
----------------------------------------------
| Type_A        |    Type_B   |      0      | -> Because Apple_Type is from index 0 in the Fruit Array
| Type_A2       |    Type_B3   |      1      | -> Because Banana_Type is from index 1 in the Fruit Array
---------------------------------------------- 

1 Answer 1

4

Using INDEX:

INDEX

The index of the element, if it is an array; otherwise NULL.

SELECT  v.value:Apple_Type,
        v.value:Banana_Type,
        v.index
FROM Table1, LATERAL FLATTEN(input => Fruits) v
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, I have been searching for this on many websites but couldn't find it. Thanks, for our help
Just complementing Lukasz answer that index order is not guaranteed, so be very careful not to use python like PK or FK in future accesses: docs.snowflake.com/en/sql-reference/functions/flatten#output

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.