2

I have this JSON

    "type": "list",
    "data": [
        {
            "id": "5bc7a3396fbc71aaa1f744e3",
            "type": "company",
            "url": "/companies/5bc7a3396fbc71aaa1f744e3"
        },
        {
            "id": "5b0aa0ac6e378450e980f89a",
            "type": "company",
            "url": "/companies/5b0aa0ac6e378450e980f89a"
        }
    ],
    "url": "/contacts/5802b14755309dc4d75d184d/companies",
    "total_count": 2,
    "has_more": false
}

I want to dynamically create columns as the number of the companies with their Ids, for example:

company_0 comapny_1
5bc7a3396fbc71aaa1f744e3 5b0aa0ac6e378450e980f89a

Tried to use BigQuery's JSON functions but I didn't get along with it.

Thank you.

2
  • did you have chance to search within SO? there are number of posts similar to this one that are answered already! Commented Aug 23, 2022 at 23:04
  • searched a lot but didn't find the same case as I have, objects inside an array with the same keys. can you please point me to a possible solution? Commented Aug 23, 2022 at 23:07

1 Answer 1

2

Consider below approach

select * except(json) from (
  select json, json_extract_scalar(line, '$.id') company, offset
  from your_table t, unnest(json_extract_array(json, '$.data')) line with offset
  where json_extract_scalar(line, '$.type') = 'company'
)
pivot (any_value(company) company for offset in (0, 1))          

if applied to sample data in your question - output is

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.