postgresqlpostgresql-14

error while converting the json column to text in PostgreSQL


I am trying to convert the json column to text

SELECT json_data->>'text' AS text
    FROM table1

it is giving below error

SQL Error [22P05]: ERROR: unsupported Unicode escape sequence Detail: \u0000 cannot be converted to text. Where: JSON data, line 2:   "j_description":...

I tried replacing the "\u0000" sequences with ''

SELECT regexp_replace(json_data, '\u0000', '', 'g')->>'text' AS text
    FROM table1 

it is giving below error

SQL Error [42883]: ERROR: function regexp_replace(json, unknown, unknown, unknown) does not exist

Hint: No function matches the given name and argument types. You might need to add explicit type casts.

I also tried with below script, but, no luck

 SELECT regexp_replace(json_data::text, '\u0000', '', 'g')->>'text' AS text
    FROM table1

 SELECT regexp_replace(cast(json_data as text, '\u0000', '', 'g')->>'text' AS text
    FROM table1

could someone advice me, please.

thank you


Solution

  • You are doing something wrong:

    Just do:

    SELECT json_data::text FROM table1
    

    Instead of:

    SELECT json_data->>'text' AS text
    FROM table1
    

    UPDATE:

    The Select should look so:

    SELECT json_data->>'j_description'::text as result from table1;
    

    UPDATE:

    SELECT regexp_replace(json_data::text, '\u0000', 'newOne')::json->>'j_description'::text as result from table1;
    

    UPDATE:

    Based on this kind of problem a good solution in my opinion contains 2 steps:

    1. Do clean of all columns and replace \u0000 to something like.

       update table1
       set json_data = REPLACE(json_data::text, '\u0000', '' )::json 
       where json_data::text like '%\u0000%';
      

    2.The select will work well without any regex_replace

    SELECT json_data->>'j_description'::text as result from table1;
    

    Finally you should do it for all columns that you need json_data here is for an example.