1

I have a column products in a table test which is of type of text in the below format:

 [{"is_bulk_product": false, "rate": 0, "subtotal": 7.17, "qty": 2, "tax": 0.90}]

It is an array with nested dictionary values. When I tried to alter the column using this:

alter table test alter COLUMN products type jsonb using products::jsonb;

I get below error:

ERROR:  22P02: invalid input syntax for type json
DETAIL:  Character with value 0x09 must be escaped.
CONTEXT:  JSON data, line 1: ...some_id": 2613, "qty": 2, "upc": "1234...
LOCATION:  json_lex_string, json.c:789
Time: 57000.237 ms (00:57.000)

how can we make sure the json is valid before altering the column ?

Thank You

1
  • 1
    Check the first function mentioned here to validate a single json-string: stackoverflow.com/questions/30187554/… Select all rows of the table and send the column you want to validate through this function, then you will see which rows are invalid. How you repair them.. is up to you. Btw, your example has a comma to much. Commented Apr 11, 2022 at 20:24

1 Answer 1

2

Your written JSON string is correct, so this SQL code execute without exception:

select '[{"is_bulk_product": false, "rate": 0, "subtotal": 7.17, "qty": 2, "tax": 0.90}]'::jsonb

Maybe the table has an incorrect JSON format in other records. You can firstly check this by selecting data, example:

select products::jsonb from test;

And you have incorrect syntax on your SQL code, you can cast products field to JSONB but not a test, test is your table name:

alter table test 
alter COLUMN products type jsonb using products::jsonb;
Sign up to request clarification or add additional context in comments.

3 Comments

corrected the SQL statement, thank you
does the text column needs to have same keys in all the records to convert it to jsonb ? this column has varying fields
@DevBabai No, it's json, every object stands on its own; there is no "document schema" or something

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.