HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlMinor

Update a json element in json datatype

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
jsondatatypeupdateelement

Problem

I can't figure how can I update an element in a PostgreSQL 9.3 datatype.

My example:

CREATE TABLE "user"
(
  id uuid NOT NULL,
  password character varying(255),
  profiles json,
  gender integer NOT NULL DEFAULT 0,
  created timestamp with time zone,
  connected timestamp with time zone,
  modified timestamp with time zone,
  active integer NOT NULL DEFAULT 1,
  settings json,
  seo character varying(255) NOT NULL,
  CONSTRAINT id_1 PRIMARY KEY (id)
)
WITH (
  OIDS=TRUE
);
ALTER TABLE "user"
  OWNER TO postgres;


The json part in "profiles"

{
"Facebook": {
"identifier": "xxxxxxxxxxx",
"profileURL": "none",
"webSiteURL": "none",
"photoURL": "none",
"displayName": "test2 test2",
"description": "none",
"firstName": "test2",
"lastName": "test2",
"gender": 2,
"language": "none",
"age": "none",
"birthDay": "none",
"birthMonth": "none",
"birthYear": "none",
"email": "test@test.com",
"emailVerified": "none",
"Added": null,
"phone": "none",
"address": "none",
"country": "none",
"region": "none",
"city": "none",
"zip": "none"
},
"Google": {
"identifier": "xxxxxxxxxxxxxxxxxxxxxx",
"profileURL": "none",
"webSiteURL": "none",
"photoURL": "none",
"displayName": "test2 test2",
"description": "none",
"firstName": "test2",
"lastName": "test2",
"gender": 2,
"language": "none",
"age": "none",
"birthDay": "none",
"birthMonth": "none",
"birthYear": "none",
"email": "test@test.com",
"emailVerified": "none",
"Added": null,
"phone": "none",
"address": "none",
"country": "none",
"region": "none",
"city": "none",
"zip": "none"
}
}


I'm using x-edit for the frontend, and I was hoping that something li

Solution

Since it's just a string, you might be able to accomplish a simple change/deletion of a node with the regex_replace function.

For example, this is how I recently deleted a certain JSON node in a table (all rows):

UPDATE my_db.my_table
SET my_column = (regexp_replace(my_column::text, ',"some_json_node":(.*),', ','))::json
WHERE NOT my_column IS NULL


Note, for all my JSON data, I keep a "version":"(n).(n)" (i.e. schema version) node in the object. That way I can update objects that comply with a specific version. Your requirements may not be that complex, but if they are, it certainly helps.

Code Snippets

UPDATE my_db.my_table
SET my_column = (regexp_replace(my_column::text, ',"some_json_node":(.*),', ','))::json
WHERE NOT my_column IS NULL

Context

StackExchange Database Administrators Q#54663, answer score: 9

Revisions (0)

No revisions yet.