Search code examples
postgresqljsonbpostgresql-9.5postgresql-10

Replace apostrophe ( ' ) in postgresql jsonb array object


Please find the below jsonb object where i need to replace all apostrophe from instruction key.

    [{
        "instruction": "Don't need to book car for M'lore location",
        "reservationNo": "TT00098272"
    },
    {
        "instruction": "Please book a car for mumbai location",
        "reservationNo": "TT00098273"
    }
 ]

Expected Result : values are replace with apostrophe

[{
            "instruction": "Dont need to book car for Mlore location",
            "reservationNo": "TT00098272"
        },
        {
            "instruction": "Please book a car for mumbai location",
            "reservationNo": "TT00098273"
        }
     ]

Solution

  • You can do a regexp_replace() after casting to text:

    postgres=# create table j (field jsonb);
    CREATE TABLE
    postgres=# insert into j values ('[{
    postgres'#         "instruction": "Don''t need to book car for M''lore location",
    postgres'#         "reservationNo": "TT00098272"
    postgres'#     },
    postgres'#     {
    postgres'#         "instruction": "Please book a car for mumbai location",
    postgres'#         "reservationNo": "TT00098273"
    postgres'#     }
    postgres'#  ]'::jsonb);
    INSERT 0 1
    postgres=# select regexp_replace(field::text,'''','','g')::jsonb from j;
                                                                                        regexp_replace                                                                                     
    ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
     [{"instruction": "Dont need to book car for Mlore location", "reservationNo": "TT00098272"}, {"instruction": "Please book a car for mumbai location", "reservationNo": "TT00098273"}]
    (1 row)