0

As an example, I have this basic table structure:

CREATE TABLE test (id serial, info json);
INSERT INTO test(info)
   VALUES ('{
             "dept":[
                     {
                      "name":"abc",
                      "desc":"hello",
                      "enabled":false
                     },
                     {
                      "name":"xyz",
                      "desc":"hello",
                      "enabled":false
                     }
                    ]
            }');

I want to update and set "enabled":true where "name" is "abc".

Laurenz Albe
  • 209,280
  • 17
  • 206
  • 263
Narender Pal
  • 11
  • 1
  • 2

1 Answers1

1

PostgreSQL 9.3 only has functions to create JSON, but no functions to use or modify it. I've already faced it before and I used the 2 trick below

  1. Cast it into text and use function regexp_replace. See the query below

    SELECT info, 
           regexp_replace(info::text,
                          '("name":"abc"[^}]+)"enabled":false',
                          E'\\1"enabled":true'
                         )::json 
    FROM test;
    

    More explanation: the \\1 represents the characters matched between ( and ) in the search string. You can find more information here.

  2. Newer versions of PostgreSQL have functions to modify JSON. So install a small instance of PostgreSQL in a newer version and use the features “foreign table” or “dblink” to update the data with the primary key. For the functions to update json and jsonb you can get more here.

Hopefully it'll help you in this case.

Laurenz Albe
  • 209,280
  • 17
  • 206
  • 263
Mabu Kloesen
  • 1,248
  • 7
  • 8