0

I use cross join to unnest nested json values, but when filed not found it returns no record. is there a solution for the below using left join somehow?

create table json_example as
select '{"id": "21397",  "fields": { "labels": [] , "subtasks": [{"id": "10217"}] }}'::jsonb as value
union all
select '{"id": "21397",  "fields": { "labels": [] ,  "subtasks" : []  }}'::jsonb

returns both rows:

select * from json_example

the below returns only one row:

select subtasks.value->>'id'  
  from json_example h cross join
       jsonb_array_elements(value->'fields'->'subtasks') as subtasks

how i can solve the above, problem to have both records?

clairvoyant
  • 195
  • 1
  • 11

2 Answers2

1

You don't need to use a cross join, a simple lateral query will do - you don't even need the LATERAL keyword when calling a table function:

select subtasks.value->>'id'  
  from json_example,
       jsonb_array_elements(value->'fields'->'subtasks') as subtasks

But you can also put it right inside your select expression:

select jsonb_array_elements(value->'fields'->'subtasks') ->> 'id'  
  from json_example
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
0

You may add on true for left join to work.

select subtasks->>'id'  
  from json_example h left join
       jsonb_array_elements(value->'fields'->'subtasks') as subtasks on true
Kaushik Nayak
  • 30,772
  • 5
  • 32
  • 45