1

I was going through the Postgres Jsonb documentation but was unable to find a solution for a small issue I'm having.

I've got a table : MY_TABLE

that has the following columns:

User, Name, Data and Purchased

One thing to note is that "Data" is a jsonb and has multiple fields. One of the fields inside of "Data" is "Attribute" but it is currently a string. How can I go about changing this to a list of strings?

I have tried using json_build_array but have not had any luck

So for example, I'd want my jsonb to look like :

   {
       "Id": 1,
       "Attributes": ["Test"]

   }

instead of

{
    "Id": 1,
    "Attributes": "Test"

}

I only care about the "Attributes" field inside of the Json, not any other fields.

2
  • Please provide sample data and expected results. Commented Mar 4, 2020 at 15:27
  • @GMB just updated the question, thanks for responding Commented Mar 4, 2020 at 15:32

1 Answer 1

1

You can do this with jsonb_set() and jsonb_build_array(), like so:

jsonb_set(js, '{Attributes}', jsonb_build_array(js->> 'Attributes'))

Demo on DB Fiddle:

with t as (select '{ "Dd":1, "Attributes":"Test"}'::jsonb js)
select 
    js, 
    jsonb_set(js, '{Attributes}', jsonb_build_array(js->> 'Attributes')) new_js
from t
js                              | new_js                           
:------------------------------ | :--------------------------------
{"Dd": 1, "Attributes": "Test"} | {"Dd": 1, "Attributes": ["Test"]}
Sign up to request clarification or add additional context in comments.

5 Comments

Thank you very much - do you know how I could use my table in the query you provided? I've replaced '{ "Id:1, "Attributes : "Test"}' with MY_TABLE.data but getting syntax issues.
@blazerix: select jsonb_set(data, ...) from mytable
I have the following: with t as (select jsonb_set(data) from public.mytable as js) select js, jsonb_set(js, '{Attributes}', jsonb_build_array(js->> 'Attributes')) new_js from t but it says function jsonb_set does not exist
@blazerix: no. Just: select data, jsonb_set(data, '{Attributes}', jsonb_build_array(data ->> 'Attributes')) new_data from mytable.
Thank you very much, this is what I was looking for. I will read more into jsonb_set and jsonb_build_array so I have a more clear understanding.

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.