Skip to content
Advertisement

Extract values from JSON with nesting

I have a problem with taking all values under the “id_ref_directory” keys.

I have a temp table:

I have a JSON, in temp table:

I have var int[]:

And I have JSON like this in “value” field:

I need to write into var_territory_listthis from JSON abowe (values of keys “id_ref_directory”):

I thought that I could solve everything with simple operators like #> but I failed. Maybe it is necessary to do it through a cycle? Thank you in advance!

Advertisement

Answer

Click: step-by-step demo:db<>fiddle

  1. jsonb_array_elements() gives you one row per array element
  2. elems -> 'id_ref_directory' gives you the expected values of these elements
  3. jsonb_agg() aggregates them into a JSON array

If you want an int array:

  1. Instead of jsonb_agg() use array_agg() after casting the elements into int values

Postgres 12 allows to use JSONpath:

Click: demo:db<>fiddle

  1. '$.territory_custom.id_ref_directory' gives you all expected elements
  2. The function aggregates the result into an array

If you want an int array:

  1. Calculate all elements into one row per element
  2. Aggregate these elements with array_agg() after casting them into int values
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement