14

I created a field name is result and type is text. I just want to update 'lat' in column. When I use this query I get syntax error. How can I do?

The column data is

"{"lat":"48.00855","lng":"58.97342","referer":"https:\/\/abc.com\/index.php"}"

Query is

update public.log set (result::json)->>'lat'=123 where id=6848202

Syntax error is

ERROR:  syntax error at or near "::"
3
  • Postgres version? Commented Nov 23, 2017 at 11:46
  • Postgres version is 9.6 Commented Nov 23, 2017 at 11:49
  • Any thoughts on how we can achieve this in postgres 9.4? Commented Mar 7, 2019 at 10:37

4 Answers 4

25

Use the jsonb concatenation operator (Postgres 9.5+):

update log
set result = result::jsonb || '{"lat":"123"}'
where id = 6848202

In Postgres 9.4 use json_each() and json_object_agg() (because jsonb_object_agg() does not exists in 9.4).

update log
set result = (
    select json_object_agg(key, case key when 'lat' then '123' else value end)
    from json_each(result)
    )
where id = 6848202

Both solutions assume that the json column is not null. If it does not contain the lat key, the first query will create it but the second will not.

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

1 Comment

In case somebody's wondering how to do this with data coming out of an already existing column, y'all can leverage json_build_object function to do this. result::jsonb || json_build_object('key', column)
1

I also tried to update json value in json type field, but couldn't find appropriate example. So I've connected to postgres DB using PgAdmin4, opened desired table and changed desired field's value, then looked at Query History to see what command it uses to change it.

So, finally, I've got the next simple python code for own purposes to update json field in postgres db:

import psycopg2

conn = psycopg2.connect(host='localhost', dbname='mydbname', user='myusername', password='mypass', port='5432')
cur = conn.cursor()
cur.execute("UPDATE public.mytable SET options = '{\"credentials\": \"required\", \"users\": [{\"name\": \"user1\", \"type\": \"string\"}]}'::json WHERE id = 8;")
cur.execute("COMMIT")

enter image description here

Comments

1

In PostgreSQL 13, You can:

update public.log set result = jsonb_set(result,'{lat}','"123"') where id=6848202;

Comments

0

In case the column is still null, you can use coalesce. The answer is provided here: PostgreSQL 9.5 - update doesn't work when merging NULL with JSON

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.