Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert postgres json to integer

I can use to_json(1) to cast int to json, but how can I convert json to int? This may be too slow:

to_json(1)::text::int 

Also, is json wrapped from a binary block (bson) or a simple wrapper of text?

like image 764
Inshua Avatar asked Nov 27 '13 07:11

Inshua


People also ask

Is JSON a datatype in PostgreSQL?

PostgreSQL offers two types for storing JSON data: json and jsonb . To implement efficient query mechanisms for these data types, PostgreSQL also provides the jsonpath data type described in Section 8.14. 7. The json and jsonb data types accept almost identical sets of values as input.

Should I use Jsonb in Postgres?

JSONB supports indexing the JSON data, and is very efficient at parsing and querying the JSON data. In most cases, when you work with JSON in PostgreSQL, you should be using JSONB.


2 Answers

What works for me (using posgtgresql 5.6) is

SELECT (tablename.jsoncolumnname->>'jsonfiledname')::int FROM tablename; 

like

SELECT (users.data->>'failed_login_attempts_count')::int FROM users; 

Assuming users table has a json column named data which is something like:

{"failed_login_attempts_count":"2","comment":"VIP"} 
like image 101
Ali Avatar answered Sep 21 '22 17:09

Ali


to_json(1)::text::int maybe too slow

But then, it's the only way.

The second part of your question is unclear.

like image 44
Denis de Bernardy Avatar answered Sep 21 '22 17:09

Denis de Bernardy