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

前端 未结 6 903
难免孤独
难免孤独 2021-01-31 07:15

I have a TEXT column containing valid JSON string.

CREATE TABLE users(settings TEXT);

INSERT INTO users VALUES (\'{\"language\":\"en\",\"gender\":\         


        
相关标签:
6条回答
  • 2021-01-31 07:59

    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;
    
    0 讨论(0)
  • 2021-01-31 08:02
    SELECT cast(settings AS json) from users;
    
    0 讨论(0)
  • 2021-01-31 08:10

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

    ALTER TABLE table1 ALTER COLUMN col1 TYPE JSON USING col1::JSON;
    
    0 讨论(0)
  • 2021-01-31 08:12

    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
    
    0 讨论(0)
  • 2021-01-31 08:20

    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';
    
    0 讨论(0)
  • 2021-01-31 08:22

    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.

    0 讨论(0)
提交回复
热议问题