I trying to append a JSON value in the Postgres table
Table structure
id | name | field
------------------------------------
1 | jack |{age:22, place:"london"}
2 | rocky|{age:34, place:"nyc"}
for the first records, I’m appending the value "NYC" to the existing value(example: {age:22, place:"London,NYC"}
and for the second record, I’m replacing the existing value "nyc" to "SFO"
update table
set field->>place = field->>place + "NYC"
where id =1
update table
set field->>place = "SFO"
where id =2
but the first record is not getting updated.
2
Answers
You may use the
||
operator andjsonb_build_object
.NB: Postgres 9.5+
DB-fiddle
+
operator never existed in PostreSQL forjson
orjsonb
types. You might’ve had||
in mind, for string concatenation which in some languages is a+
.update
you need to address a field. By using->>
operator to the left of=
, you’re addressing a value extracted from the field instead, which breaks the syntax.That being said, this works on 9.3: