How to convert postgres json to integer

JsonPostgresql

Json Problem Overview


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?

Json Solutions


Solution 1 - Json

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"}

Solution 2 - Json

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

But then, it's the only way.

The second part of your question is unclear.

Solution 3 - Json

The PostgreSQL 9.3 JSON support is simply validated json text.

In 9.4 and newer you can use jsonb.

"may be too slow" doesn't make a ton of sense. What makes you think it's too slow? Did you test and benchmark? If it's "too slow" what speed would not be too slow, i.e. what do you expect?

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionInshuaView Question on Stackoverflow
Solution 1 - JsonAliView Answer on Stackoverflow
Solution 2 - JsonDenis de BernardyView Answer on Stackoverflow
Solution 3 - JsonCraig RingerView Answer on Stackoverflow