1

I have the following data structure:

create table test (tags VARCHAR, tags_json VARCHAR);

insert into test (tags, tags_json)
values ('A B', '["A", "B"]')

And I want to convert the column tags to a JSON column. If I were to do it with the tags_json column is pretty easy:

select tags_json::JSON from test

But when I run it using the tags column,

select tags::JSON from test

I get

SQL Error [22P02]: ERROR: invalid input syntax for type json

How can I convert the column tags to a JSON column in postgresql?

6
  • IS the problem that 'A B' is not valid JSON? Commented Aug 13, 2020 at 7:12
  • yes, that is what I think Commented Aug 13, 2020 at 7:13
  • What do you want to happen with the invalid JSON? What do you expect 'A B' to be in a JSON representation? Commented Aug 13, 2020 at 7:14
  • the same as '["A", "B"]' Commented Aug 13, 2020 at 7:14
  • Are all values in that column space separated words? Commented Aug 13, 2020 at 7:15

1 Answer 1

3

You need to first convert your "plain text" to an array, then you can use to_jsonb() to convert that to a proper JSON value:

select to_jsonb(regexp_split_to_array(tags, '\s+'))
from test;

If you want to permanently change the column's data type, you can use that expression in an ALTER statement:

alter table test
  alter tags type jsonb 
     using to_jsonb(regexp_split_to_array(tags, '\s+'));
Sign up to request clarification or add additional context in comments.

Comments

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.