1

I am using postgresql 9.4

I have one json column in the table and it contains the value:

"{
  "title" : "risk",
  "name"  : "David"
}"

I have to perform two functionality

  1. Update the name value to "John"
  2. Insert the "city" : "paris"

my final value should be in my table column

"{
  "title" : "risk",
  "name"  : "John",
  "city"  : "paris"
}"

Basically, I want update and insert query for this json column and I can not change the database to higher version

1
  • 1
    Hi. Please read How to Ask. Please explain how the documentation doesn't tell you this. Commented Nov 10, 2017 at 11:04

2 Answers 2

1

smth like:

update table 
set jbcolumn = json_build_object('title',jbcolumn->>'title','name','John','city','Paris') where bcolumn->>'name' = 'David

in postgres 9.4

https://www.postgresql.org/docs/9.4/static/functions-json.html

json_build_object(VARIADIC "any")

Sign up to request clarification or add additional context in comments.

2 Comments

I have tried this but getting ERROR : function json_build_object(unknown, unknown, unknown, unknown, unknown, unknown) does not exist
This was helped me somewhat but need to update little bit
1

There is useful || operator for JSON type in the later versions of PostgreSQL. For 9.4 version you can to create it yourself:

create function my_json_cat(json, json) returns json stable strict language sql as $$
  select json_object_agg(coalesce(x.key, y.key), coalesce(y.value, x.value))
  from json_each($1) as x full join json_each($2) as y on (x.key = y.key)
$$;

create operator || (
  leftarg=json, rightarg=json,
  procedure=my_json_cat);


with t(x,y) as (values('{
  "title" : "risk",
  "name"  : "David"
}'::json, '{
  "title" : "risk",
  "name"  : "John",
  "city"  : "paris"
}'::json))
select x || y from t;

So your final statement could be

update your_table set
  your_column = your_column || '{"name": "John", "city": "paris"}'
where ...

After upgrade to the later version of PostgreSQL just remove function and operator declarations from your DB script, nothing else should be changed.

Demo.

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.