I have a TEXT
column containing valid JSON string.
CREATE TABLE users(settings TEXT);
INSERT INTO users VALUES (\'{\"language\":\"en\",\"gender\":\
Adding to another comment, here is a one-liner in a query(without the need to update)
regexp_replace(trim(both '"' from settings::text), '\\"', '"', 'g')::json as column_name;
SELECT cast(settings AS json) from users;
Here is a solution from Postgresql: Converting TEXT columns to JSON:
ALTER TABLE table1 ALTER COLUMN col1 TYPE JSON USING col1::JSON;
So I had an issue where the text was JSON. If you have this issue use this query instead. Where COLUMN is the column that contains the JSONB or JSON datatype and ATTRIBUTE is the attribute of the JSON that is a string, that you want converted into JSON.
The text will look like this, "{\"junk5\": 283774663, \"junk2\": 0, \"junk1\": 1218478497, \"junk3\":1923, \"junk4\": 63278342}"
SELECT CAST(TRIM(both '"' from jsonstring) as JSON)
FROM (
SELECT REPLACE(cast(COLUMN->'ATTRIBUTE' as text), '\"', '"')
as jsonString from TABLE where cast(COLUMN->'ATTRIBUTE' as text)LIKE '%\\%'
) as JSON_CONVERTING
If you need an index on it, create an immutable function that takes the json as input and yields the field you want as output in a pl language, e.g.:
create function extract_language(text) returns text as $$
-- parse $1 as json
-- return $1.language
$$ language whatever immutable;
Then add an index on the expression:
create index users_language on users(extract_language(settings));
The index will then (potentially) get used in queries such as:
select * from users where extract_language(settings) = 'en';
Or in a shortest way than Reza:
SELECT settings::json FROM users;
Then, for selecting language for instance:
SELECT settings::json->>'language' FROM users;
More details on the official documentation.