skip to Main Content

I have this data in a json column

#mycolumn
{
  "key": "KEY",
  "elements": [
    { "name": "NAME_1" },
    { "name": "NAME_2" }
    { "name": "NAME_3" }
  ]
}

I want to select all the elements[*].name.

I have tried:

select JSON_EXTRACT_PATH_TEXT(mycolumn, 'elements[].name')
select JSON_EXTRACT_PATH_TEXT(mycolumn, 'elements[*].name')
select JSON_EXTRACT_PATH_TEXT(mycolumn, 'elements[0,1,2].name')

Nothing works.

This works:

select JSON_EXTRACT_PATH_TEXT(mycolumn, 'elements[0].name')

But this returns only the first element.name

How can I get all the names?

2

Answers


  1. You need to use LATERAL FLATTEN, like this:

    with jdata as (
    SELECT try_PARSE_JSON(column1) AS mycolumn
    FROM VALUES
    ('{
      "key": "KEY",
      "elements": [
        { "name": "NAME_1" },
        { "name": "NAME_2" },
        { "name": "NAME_3" }
      ]
    }'
    )
    )
    select e.value:name::string
    from jdata j, LATERAL FLATTEN(INPUT => mycolumn:elements) e;
    
    Login or Signup to reply.
  2. Using a higher order function TRANSFORM:

    SELECT TRANSFORM(mycolumn:elements, x -> x:name) FROM t;
    

    Output:

    enter image description here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search