Skip to content
Advertisement

How to convert fields to JSON in Postgresql

I have a table with the following schema (postgresql 14):

message are only string, phrases. sentiment is a string, only one word classification are string but can have 1 to many word comma separated

I would like to create a json field with these columns, like this:

Also, if possible, is there a way to consider the classification this way:

Advertisement

Answer

The first part of question is easy – Postgres provides functions for splitting string and converting to json:

The second part is harder – your want json to have variable number of attributes, mixed of grouped and nongrouped data. I suggest to unwind all attributes and then assemble them back (note the numbered CTE is actually not needed if your real table has id – I just needed some column to group by):

DB fiddle

Advertisement