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?

Tom
  • 33,626
  • 31
  • 85
  • 109

1 Answers1

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

Mikhail Berlyant
  • 165,386
  • 8
  • 154
  • 230