代码之家  ›  专栏  ›  技术社区  ›  Brian

如何更新PostgreSQL中存储在文本字段中的json数据?

  •  1
  • Brian  · 技术社区  · 7 年前

    我有一张桌子 services properties 是谁的类型 text

    有 json 存储在 专栏。

    我可以询问 json psql 这样地:

    SELECT * FROM services WHERE properties::json->>'url' = 'www.example.com';
    

    但我无法更新 json

    UPDATE 
       services SET properties::json->>'url' = 'www.mydomain.com' 
    WHERE 
       properties::json->>'url' = 'www.example.com';
    

    这个 UPDATE 上面的命令生成错误:

    ERROR:  syntax error at or near "::"
    LINE 1: UPDATE services SET properties::json->>'url' = 'www.....
    

    url 内部字段 性质 专栏?

    指挥部?

    2 回复  |  直到 7 年前
        1
  •  2
  •   dwir182    7 年前

    我不知道你们公司的结构 JSON 所以我用我的样品。

    你可以用 REPLACE 作用于 一串 example domain 在那之后,你投给 JSON properties text 到 json .

    :

    update services
    set properties = replace(properties,'example','domain')::jsonb
    where properties::json->>'url' = 'www.example.com';
    

    你可以在这里看到 Demo

        2
  •  4
  •   Kaushik Nayak    7 年前

    您应该将记录存储为 JSON TEXT 因此,在所有地方都不需要进行类型转换。

    jsonb_set

    UPDATE 
       services SET properties = jsonb_set(properties::jsonb,
                     '{url}' , '"www.mydomain.com"' )::text
    WHERE 
       properties::json->>'url' = 'www.example.com';
    

    Demo