1

I have rows like this in my snowflake database:

+-----+-----+-----+
| Foo | Bar | Baz |
+-----+-----+-----+
| A   | a   | []  |
| A   | b   | []  |
| B   | a   | []  |
| B   | b   | []  |
+-----+-----+-----+

I want to convert this into:

  "A": {
    "a": [],
    "b": []
  },
  "B": {
    "a": [],
    "b": []
  }

2 Answers 2

1

Snowflake allows to achieve the desired effect with SQL:

CREATE OR REPLACE TABLE t
AS
SELECT 'A' AS foo, 'a' AS bar, PARSE_JSON('[]') AS Baz
UNION ALL SELECT 'A' AS foo, 'b' AS bar, PARSE_JSON('[]') AS Baz
UNION ALL SELECT 'B' AS foo, 'a' AS bar, PARSE_JSON('[]') AS Baz
UNION ALL SELECT 'B' AS foo, 'b' AS bar, PARSE_JSON('[]') AS Baz;


SELECT OBJECT_AGG(foo, s) AS result
FROM (SELECT foo, OBJECT_AGG(bar, baz) AS s
      FROM t
      GROUP BY foo) sub;

Output:

{
  "A": {
    "a": [],
    "b": []
  },
  "B": {
    "a": [],
    "b": []
  }
}
Sign up to request clarification or add additional context in comments.

Comments

0

You can try using pandas to read sql data and convert it to nested json

Refer to Convert Pandas Dataframe to nested JSON

2 Comments

I would like to keep it as SQL
@maxisme - ok ! Please update the question title and also add details about DB & your requirement as well

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.