I have a table (log_table) and in this table there is a nested array json field (activities). With using this activities field, I want to normalize my row.
log_table:
- id:long- activities:json- date:timestampexample activities field:
[ { "actionType":"NOTIFICATION", "items":null }, { "actionType":"MUTATION", "items":[ { "id":387015007, "name":"epic", "value":{ "currency":"USD", "amount":1.76 } }, { "id":386521039, "name":"test", "value":{ "currency":"USD", "amount":1.76 } } ] }]As query, I've tried:
select * from log_table l, json_array_elements(l.activities) elems,json_array_elements(elems->'items') obj;With this query, I got error like below:
ERROR: cannot call json_array_elements on a scalarIs there any suggestion?
1 Answer1
The lack ofitems should be marked as[null], notnull. You can use the case expression to correct this, e.g.:
select elems->>'actionType' as action_type, objfrom log_tablecross join jsonb_array_elements(l.activities::jsonb) elemscross join jsonb_array_elements(case elems->'items' when 'null' then '[null]' else elems->'items' end) obj action_type | obj--------------+--------------------------------------------------------------------------------- NOTIFICATION | null MUTATION | {"id": 387015007, "name": "epic", "value": {"amount": 1.76, "currency": "USD"}} MUTATION | {"id": 386521039, "name": "test", "value": {"amount": 1.76, "currency": "USD"}}(3 rows)Explore related questions
See similar questions with these tags.

