PostgreSQL 9.2 - Convert TEXT json string to type json/hstore

徘徊边缘 提交于 2019-12-20 11:49:41

问题


I have a TEXT column containing valid JSON string.

CREATE TABLE users(settings TEXT);

INSERT INTO users VALUES ('{"language":"en","gender":"male"}');
INSERT INTO users VALUES ('{"language":"fr","gender":"female"}');
INSERT INTO users VALUES ('{"language":"es","gender":"female"}');
INSERT INTO users VALUES ('{"language":"en","gender":"male"}');

I want to transform some fields into a query-able format.

A REGEXP_REPLACE for each field would do (language field and gender field). But since it's valid JSON, is there way to:

  • Convert into JSON type
  • Convert into hstore type
  • Or any other feasible ways

SQLFiddle: http://sqlfiddle.com/#!12/54823


回答1:


SELECT cast(settings AS json) from users;



回答2:


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.




回答3:


Here is a solution from Postgresql: Converting TEXT columns to JSON:

ALTER TABLE table1 ALTER COLUMN col1 TYPE JSON USING col1::JSON;



回答4:


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';



回答5:


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


来源:https://stackoverflow.com/questions/16074375/postgresql-9-2-convert-text-json-string-to-type-json-hstore

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!