2

I have a JSON field on big query table and currently i'm using the following method to do the extraction from a id element (for example):

coalesce(
   nullif(JSON_EXTRACT(e.event_payload, 'content_id'), ''),
   nullif(JSON_EXTRACT(e.event_payload, 'cid'), ''),
   nullif(JSON_EXTRACT(e.event_payload, 'c_id'), ''),
   ...
  ) AS content_id,

I don't have a pattern on this JSON's fields... Is possible use REGEX with JSON_EXTRACT on big query like this?

JSON_EXTRACT(e.event_payload, "(content_id|cid|c_id)") as content_id
2
  • Is is possible for all three keys to be present? Commented Mar 13, 2019 at 12:27
  • No, these keys represent the same information, my problem is that JSON's have different origin, so they do not follow the same pattern... Commented Mar 13, 2019 at 12:32

2 Answers 2

3

You can replace the possible field names and then perform extraction:

SELECT
  JSON_EXTRACT(
    REGEXP_REPLACE(e.event_payload, r'"c\_?id"', '"content_id"'),
    '$.content_id') as content_id
FROM dataset.table

As a self-contained example:

WITH T AS (
  SELECT '{"cid": {"a": 1}}' AS event_payload UNION ALL
  SELECT '{"content_id": {"b": 2}}' UNION ALL
  SELECT '{"c_id": {"c": 3}}'
)
SELECT
  JSON_EXTRACT(
    REGEXP_REPLACE(e.event_payload, r'"c\_?id"', '"content_id"'),
    '$.content_id') as content_id
FROM T AS e
Sign up to request clarification or add additional context in comments.

Comments

0

You can cast your json response to string via JSON_VALUE

eg.

SELECT 

JSON_VALUE(json_specific_column_here,'$.product.en.content')  as stringified_value

FROM

`my-bq-project.my-database.my-datacontent`

This will then let you run string filters like regex over it without the dreaded JSON related type errors.

ref: https://cloud.google.com/bigquery/docs/reference/standard-sql/json_functions#json_value

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.