Querying Postgres 9.3 by json field is really great. However i couldn't find a formal way to update the json object, for which i use an internal function written in plpythonu based on previous post (How do I modify fields inside the new PostgreSQL JSON datatype?):
CREATE OR REPLACE FUNCTION json_update(data json, key text, value json)
RETURNS json AS
$BODY$
from json import loads, dumps
if key is None: return data
js = loads(data)
js[key] = value
return dumps(js)
$BODY$
LANGUAGE plpythonu VOLATILE
It works really well when my json updates remains flatten and simple. Say "chat" is a json type filed in "GO_SESSION" table, and contains {"a":"1","b":"2"}, the following code will change 'b' value and turn "chat" to be {"a":"1","b":"5"}
update "GO_SESSION" set chat=json_update(chat,'b','5') where id=3
The problem is when i'm trying to assing 'b' another object rather than a simple value:
update "GO_SESSION" set chat=json_update(chat,'b','{"name":"steve"}') where id=3
The result in database is 'b' containing an escaped string rather than a real json object:
{"a": "1", "b": "{\"name\":\"steve\"}"}
I have tried different ways to unescape or dump my json in order to keep 'b' an object, but couldn't find a solution.
Thank you