1

I came across this question on how to update nth element of array, but it has nested json values in it instead of a plain array of strings.

Here are some sample json values from jsonb column of the table.

{"pattern": {"values": ["foo", "edfgh"]}}
{"pattern": {"values": ["abc", "abdhi", "foo"]}}
{"pattern": {"values": ["these", "abcd", "para", "avil"]}}

We can select the nth element using

select data #> '{pattern, values, 0}' from table;

How can we loop through array and update foo to bar if it is present in that array?

asked Apr 24, 2019 at 6:20
6
  • Json values are not valid please correct that Commented Apr 24, 2019 at 20:24
  • @SahapAsci Corrected it. Thanks. Commented Apr 25, 2019 at 7:04
  • Copy of dba.stackexchange.com/questions/193390/… Commented Apr 25, 2019 at 7:21
  • @A.J.Alger The question is not the same. The value foo can be anywhere in array. Commented Apr 25, 2019 at 9:13
  • how about if there is more than one "foo" in the array ? Commented Apr 29, 2019 at 10:54

1 Answer 1

4

You can use a query like the one below;

UPDATE table SET
 data = jsonb_set(data,'{pattern, values}', ((data->'pattern'->'values') - 'foo') || '["bar"]' )
WHERE
 (data #> '{pattern, values}') ? 'foo';

Details;

First you have to find records which have "foo" value in "values" array;

(data #> '{pattern, values}') ? 'foo'

After that remove the value "foo" from the array;

((data->'pattern'->'values') - 'foo')

Create a new array by concatenating your new value(s).

((data->'pattern'->'values') - 'foo') || '["bar"]'

Replace new array with the old one.

jsonb_set(data,'{pattern, values}', new_array)
answered Apr 25, 2019 at 9:22
1
  • This replaces the element but doesn't preserve the order. Is there a way to update it and preserve order also? Commented Apr 26, 2019 at 4:28

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.