3

I have a json in bigQuery

{
  "actors": {
    "stooges": [
      {
        "id": 1,
        "name": "Larry"
      },
      {
        "id": 2,
        "name": "Curly"
      },
      {
        "id": 3,
        "name": "Moe"
      }
    ]
  }
}

How do I extract each of the .names in bigQuery.

["Larry", "Curly", "Moe"]

Here are some handy bigQuery compatible statements(based on above json).

-- Declaring a bigQuery variable 
DECLARE json_data JSON DEFAULT (SELECT PARSE_JSON('{ "actors": {"stooges": [{"id": 1,"name": "Larry"},{"id": 2,"name": "Curly"},{"id": 3,"name": "Moe"}]}}'));

-- Select statement. But this is no good for my use case since I don't want to specify element index ([0]) as the array size is dynamic
SELECT JSON_EXTRACT(json_data, '$.actors.stooges[0].name');

1 Answer 1

5

You may try and consider below approach using JSON_EXTRACT_ARRAY() then unnest it and then use JSON_EXTRACT_SCALAR() to extract the values. You may refer to this documentation for more details in BigQuery JSON functions.

select ARRAY(
  SELECT JSON_EXTRACT_SCALAR(json_array, '$.name') from UNNEST(JSON_EXTRACT_ARRAY(json_data,"$.actors.stooges"))json_array
)extracted_names

Output: enter image description here

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.