2

I have a JSON field my table which looks like this. There could be any number of comments in each entry.

{
    "entry": 1234,
    "comment_6789": {
        "_seconds": 1614864327,
        "_nanoseconds": 606000000,
        "message": "hello world"
    },
    "comment_4564564": {
        "_seconds": 1614864327,
        "_nanoseconds": 606000000,
        "message": "hello mars"
    }
}

After reading this question I know I can use JSON_EXTRACT_ARRAY, but I'm a bit unsure on how to target each of the comment_ entries, since they will have different ids?

1 Answer 1

2

Consider below

#standardSQL
with `project.dataset.table` as (
  select 1 id, '''
  {
    "entry": 1234,
    "comment_6789": {
        "_seconds": 1614864327,
        "_nanoseconds": 606000000,
        "message": "hello world"
    },
    "comment_4564564": {
        "_seconds": 1614864327,
        "_nanoseconds": 606000000,
        "message": "hello mars"
    }
  }  
  '''  col
)
select id, comment,
  json_value(kv, '$._seconds') seconds,
  json_value(kv, '$._nanoseconds') nanoseconds,
  json_value(kv, '$.message') message
from `project.dataset.table`,
unnest(regexp_extract_all(col, r'comment_\d+')) comment,
unnest([struct(regexp_extract(col, r'"' || comment || '": ({[^{}]+})') as kv)])      

with 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.