webjunkie
webjunkie

Reputation: 1184

Reconstruct JSONB Nested Arrays

I have the following JSONB column called value.

create temp table settings as
select 
   '{"favorites": [
      {
      "listings": [
       {"id": "aa92f346-7a93-4443-949b-4eab0badd983", "version": 1},
       {"id": "cd92e346-6b04-3456-050a-5eeb0bddd027", "version": 3},
       {"id": "cd92e346-6b04-3456-050a-5eeb0bddd333", "version": 2}
       ]
      }
]}'::jsonb as value;

So I'm trying to remove items from this nested array and reconstruct it like so

select jsonb_set(value,'{favorites}',jsonb_set('{}','{listings}', 
       jsonb_agg(new_elems))   ) as ne  from settings s ,
lateral ( select  jsonb_array_elements(elem->'listings')as new_elems 
       from jsonb_array_elements(value->'favorites')elem) sets where  
       sets.new_elems->>'id' != 'aa92f346-7a93-4443-949b-4eab0badd983' 
       group by s.value

Which works but the "favorites" array is flattened.

Instead of

"{"favorites": [{"listings": [{"id": "cd92e346-6b04-3456-050a-5eeb0bddd027", "version": 3}, {"id": "cd92e346-6b04-3456-050a-5eeb0bddd333", "version": 2}]}]}"

I get

"{"favorites": {"listings": [{"id": "cd92e346-6b04-3456-050a-5eeb0bddd027", "version": 3}, {"id": "cd92e346-6b04-3456-050a-5eeb0bddd333", "version": 2}]}}"

Does anyone have an idea on how can I solve this?.

Upvotes: 0

Views: 391

Answers (1)

Haleemur Ali
Haleemur Ali

Reputation: 28283

you can create jsonb arrays by using the functions JSONB_AGG or JSON_BUILD_ARRAY. JSONB_AGG is an aggregate function, whereas JSONB_BUILD_ARRAY puts all provided arguments in an array.

Below, I used JSONB_BUILD_ARRAY to make favorites into an json array rather than a key-value

SELECT 
  JSONB_SET(
    '{}', '{favorites}', 
    JSONB_BUILD_ARRAY(
      JSONB_SET('{}', '{listings}', JSONB_AGG(listings))
    )
  )
FROM settings,
LATERAL (SELECT 
           JSONB_ARRAY_ELEMENTS(JSONB_ARRAY_ELEMENTS(value->'favorites')->'listings') listings
         FROM settings) listings
WHERE listings.listings->>'id' != 'aa92f346-7a93-4443-949b-4eab0badd983'

Upvotes: 1

Related Questions