I am using POSTGRES SQL JSON.
In json column the value is stored as array which I want to update using SQL query
{"roles": ["Admin"]}The output in table column should be
{"roles": ["SYSTEM_ADMINISTRATOR"]}I tried different queries but it is not working.
UPDATE public.bo_userSET json = jsonb_set(json, '{roles}', to_jsonb('SYSTEM_ADMINISTRATOR')::jsonb, true);UPDATE public.bo_userSET json = jsonb_set(json, '{roles}', to_jsonb('["SYSTEM_ADMINISTRATOR"]')::jsonb, true);ERROR: could not determine polymorphic type because input has type unknownSQL state: 42804Kindly help me with the query
- Sorry fixed the tag, it is v13Nitin Mukesh– Nitin Mukesh2021-07-20 05:46:03 +00:00CommentedJul 20, 2021 at 5:46
- This would be so much easier with a properly normalized data model. I assume, something like
["Admin", "User"]should be changed to["SYSTEM_ADMINISTRATOR", "User"]?user330315– user3303152021-07-20 05:49:45 +00:00CommentedJul 20, 2021 at 5:49 - Yeah that would be another scenario, but at the moment it is to update the value at 0 index. The second would be to add in Array.Nitin Mukesh– Nitin Mukesh2021-07-20 05:55:04 +00:00CommentedJul 20, 2021 at 5:55
2 Answers2
but at the moment it is to update the value at 0 index
That can be done using an index based "path" forjsonb_set()
update bo_user set "json" = jsonb_set("json", '{roles,0}'::text[], '"SYSTEM_ADMINISTRATOR"')where "json" #>> '{roles,0}' = 'Admin'The "path"'{roles,0}' references the first element in the array and that is replaced with the constant"SYSTEM_ADMINISTRATOR"' Note the double quotes inside the SQL string literal which are required for a valid JSON string
The WHERE clause ensures that you don't accidentally change the wrong value.
1 Comment
So this worked.
UPDATE public.bo_userSET json = jsonb_set(json, '{roles}', ('["SYSTEM_ADMINISTRATOR"]')::jsonb, true)where id = '??';2 Comments
Explore related questions
See similar questions with these tags.