2

I'm getting a headache trying to figure out how to read a JSON with the following format in Athena

{
  "id": "1",
  "key1": {
    "dynamic_key_here": [
      {"id": "A", "key2": "content I want"}
    ]
  }
}

Let's call this column "data", and the table it's from "info"

With a SELECT json_extract(data, '$.key1') FROM info I can get to the second layer and retrieve it as a json, but here I'm stuck because the key of this second layer is dynamic, I don't know it in advance. All I need is the content of the string contained in key2 in that second layer, (it's a 1:1 relation with what's outside the json in the table, basically it's just like adding a column to my table, no unnesting needed) can anyone help?

1 Answer 1

1

There are multiple ways to achieve that.

For example by using the ability to cast JSON to MAP:

-- sample data
WITH dataset(data) as (
    values ('{
          "id": "1",
          "key1": {
            "dynamic_key_here": [
              {"id": "A", "key2": "content I want"}
            ]
          }
        }')
)

-- query
select json_extract(content, '$.key2') result
from dataset
, unnest(map_values(cast(json_extract(data, '$.key1') as map(varchar, array(json))))) as t(inner_arr)
, unnest(inner_arr) as tt(content);

Output:

      result
------------------
 "content I want"

Another approach is to use json-query:

-- query
select json_query(data, 'lax $.key1.*.key2' WITH  ARRAY WRAPPER) result
from dataset;

Output:

       result
--------------------
 ["content I want"]
Sign up to request clarification or add additional context in comments.

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.