Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgres: How to convert a json string to text?

Json value may consist of a string value. eg.:

postgres=# SELECT to_json('Some "text"'::TEXT);      to_json -----------------  "Some \"text\"" 

How can I extract that string as a postgres text value?

::TEXT doesn't work. It returns quoted json, not the original string:

postgres=# SELECT to_json('Some "text"'::TEXT)::TEXT;      to_json -----------------  "Some \"text\"" 

Thanks.

P.S. I'm using PostgreSQL 9.3

like image 959
e79ene Avatar asked Nov 30 '14 16:11

e79ene


People also ask

How do I query JSON data in PostgreSQL?

Querying the JSON documentPostgreSQL has two native operators -> and ->> to query JSON documents. The first operator -> returns a JSON object, while the operator ->> returns text. These operators work on both JSON as well as JSONB columns. There are additional operators available for JSONB columns.

What is -> in PostgreSQL?

PostgreSQL provides two native operators -> and ->> to help you query JSON data. The operator -> returns JSON object field as JSON. The operator ->> returns JSON object field as text.

Can you store any string in a JSON Postgres data type?

You can save any valid json value to either json or to a jsonb column. But you cannot bind it as string/ text / varchar , if you use prepared statements (use casts instead in sql, like UPDATE ... SET json_col = $1::json or bind it as unknown ).

How do I convert a string to JSON?

String data can be easily converted to JSON using the stringify() function, and also it can be done using eval() , which accepts the JavaScript expression that you will learn about in this guide.


2 Answers

In 9.4.4 using the #>> operator works for me:

select to_json('test'::text) #>> '{}'; 

To use with a table column:

select jsoncol #>> '{}' from mytable; 
like image 169
Ian Timothy Avatar answered Oct 15 '22 21:10

Ian Timothy


There is no way in PostgreSQL to deconstruct a scalar JSON object. Thus, as you point out,

select  length(to_json('Some "text"'::TEXT) ::TEXT); 

is 15,

The trick is to convert the JSON into an array of one JSON element, then extract that element using ->>.

select length( array_to_json(array[to_json('Some "text"'::TEXT)])->>0 ); 

will return 11.

like image 39
Robert M. Lefkowitz Avatar answered Oct 15 '22 19:10

Robert M. Lefkowitz