Как прочитать значения ключа JSON в виде столбца данных в Snowflake? - PullRequest
0 голосов
/ 25 апреля 2020

У меня есть образец ниже JSON:

{
   "Id1": {
      "name": "Item1.jpg",
      "Status": "Approved"
   },
   "Id2": {
      "name": "Item2.jpg",
      "Status": "Approved"
   }
}

, и я пытаюсь получить следующий вывод:

_key    name        Status
Id1     Item1.jpg   Approved
Id2     Item2.jpg   Approved

Есть ли способ, которым я могу добиться этого в Снежинке используя SQL?

1 Ответ

0 голосов
/ 25 апреля 2020

Вы должны использовать тип данных Snowflake VARIANT в любом столбце, содержащем данные JSON. Давайте разберем это шаг за шагом:

create temporary table FOO(v variant); -- Temp table to hold the JSON. Often you'll see a variant column simply called "V"

-- Insert into the variant column. Parse the JSON because variants don't hold string types. They hold semi-structured types.
insert into FOO select parse_json('{"Id1": {"name": "Item1.jpg", "Status": "Approved"}, "Id2": {"name": "Item2.jpg", "Status": "Approved"}}');

-- See how it looks in its raw state
select * from FOO;

-- Flatten the top-level JSON. The flatten function breaks down the JSON into several usable columns
select * from foo, lateral flatten(input => (foo.v)) ;

-- Now traverse the JSON using the column name and : to get to the property you want. Cast to string using ::string.
-- If you must have exact case on your column names, you need to double quote them.
select  KEY                     as "_key",
        VALUE:name::string      as "name",
        VALUE:Status::string    as "Status"
from FOO, lateral flatten(input => (FOO.V)) ;
...