更新json数据类型中的json元素


14

我不知道如何更新PostgreSQL 9.3数据类型中的元素。

我的例子:

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;

“个人资料”中的json部分

{
    "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"
    }
}

我在前端使用x-edit,但我希望这样的方法行得通,但它不行:

UPDATE public.user 
SET "profiles"->'Facebook'->'social'->'facebook' = 'test' WHERE` id='id'

我似乎找不到有关如何更新json数据类型的任何信息。

Answers:


7

由于它只是一个字符串,因此您可以使用该regex_replace函数完成节点的简单更改/删除。

例如,这就是我最近删除表(所有行)中的某个JSON节点的方式:

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

注意,对于我所有的 JSON数据,我"version":"(n).(n)"在对象中保留了一个(即架构版本)节点。这样,我可以更新符合特定版本的对象。您的要求可能并不那么复杂,但是如果确实如此,它肯定会有所帮助。


我需要像col名称height = {''unit':'cms','value':150}之类的json对象使用
Rahul Dapke

3

我认为您将必须更新Postgres 9.3上的完整字段,至少这是文档告诉我的。

如果我没有记错的话,在JSON文档中更新单个元素将在9.4中进行。


2

尝试这个

UPDATE Tablename
SET columnname = replace(columnname::TEXT,'"name":','"my-other-name"')::jsonb 
WHERE id = 1;

我需要JSON对象(例如col name height = {'unit':'cms','value':150})来使用
Rahul Dapke
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.