0

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?.

1 Answer 1

1

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'
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.