13

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 "::"
klin
  • 112,967
  • 15
  • 204
  • 232
Fatih Doğan
  • 417
  • 1
  • 4
  • 16

4 Answers4

23

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.

klin
  • 112,967
  • 15
  • 204
  • 232
  • 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)` – Joan Gil Oct 12 '21 at 16:23
1

In PostgreSQL 13, You can:

update public.log set result = jsonb_set(result,'{lat}','"123"') where id=6848202;
jian
  • 4,119
  • 1
  • 17
  • 32
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

0

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

Gryu
  • 2,102
  • 2
  • 16
  • 29