4

I have a jsonb field in PostgreSQL with the following content:

{ "object": { "urls": "A;B;C" } }

What I want to do isupdate the value ofurls inside the object and transform the string with semicolon separated values into a JSON array. So the result should look like this:

{ "object" : { "urls": ["A", "B", "C"] } }

I found out how to get a JSON array. Using

to_json(string_to_array(replace((json->'object'->'urls')::text, '"',''), ';'));

gives me["A", "B", "C"] (I think there should be a better way of doing itwithout the conversion json -> text -> array -> json. Suggestions are welcome)

But how do I update theurls field with the json array now? Probably I have to usejsonb_set?

askedJan 5, 2017 at 10:05
mxlse's user avatar

1 Answer1

5

Usejsonb and the functionjsonb_set():

create table my_table(id int primary key, jdata jsonb);insert into my_table values(1, '{ "object": { "urls": "A;B;C" } }');update my_tableset jdata = jsonb_set(        jdata,         array['object', 'urls'],         to_jsonb(string_to_array(replace((jdata->'object'->'urls')::text, '"',''), ';'))        )returning *; id |                jdata                ----+-------------------------------------  1 | {"object": {"urls": ["A", "B", "C"]}}(1 row)
answeredJan 5, 2017 at 10:15
klin's user avatar
Sign up to request clarification or add additional context in comments.

1 Comment

It worked well. I just had to addWHERE jdata->'object'->'urls' IS NOT NULL. Otherwise those rows had null as json (or jdata in your case).

Your Answer

Sign up orlog in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

By clicking “Post Your Answer”, you agree to ourterms of service and acknowledge you have read ourprivacy 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.