jsonstringpostgresqlselectjsonb

Convert JSONB to minified (no spaces) String


If I convert a text value like {"a":"b"} to JSONB and then back to text a space () is added between the : and the ".

psql=> select '{"a":"b"}'::jsonb::text;
    text    
------------
 {"a": "b"}
(1 row)

How can I convert a text to a jsonb, so I can use jsonb functions, and back to text to store it?


Solution

  • From the docs:

    https://www.postgresql.org/docs/12/datatype-json.html

    "Because the json type stores an exact copy of the input text, it will preserve semantically-insignificant white space between tokens, as well as the order of keys within JSON objects. Also, if a JSON object within the value contains the same key more than once, all the key/value pairs are kept. (The processing functions consider the last value as the operative one.) By contrast, jsonb does not preserve white space, does not preserve the order of object keys, and does not keep duplicate object keys. If duplicate keys are specified in the input, only the last value is kept."

    So:

    create table json_test(fld_json json, fld_jsonb jsonb);
    insert into json_test values('{"a":"b"}', '{"a":"b"}');
     select * from json_test ;
     fld_json  | fld_jsonb  
    -----------+------------
     {"a":"b"} | {"a": "b"}
    (1 row)
    

    If you want to maintain your white space or lack of it use json. Otherwise you will get a pretty print version on output with jsonb. You can use json functions/operators on json type though not the jsonb operators/functions. More detail here:

    https://www.postgresql.org/docs/12/functions-json.html

    Modifying your example:

    select '{"a":"b"}'::json::text;
       text    
    -----------
     {"a":"b"}