如何将postgres json转换为整数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20236421/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 20:04:45  来源:igfitidea点击:

How to convert postgres json to integer

jsonpostgresql

提问by Inshua

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)将 int 转换为 json,但是如何将 json 转换为 int?这可能太慢了:

to_json(1)::text::int

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

另外,json 是从二进制块 (bson) 还是简单的文本包装器包装的?

回答by Ali

What works for me (using posgtgresql 5.6) is

对我有用的(使用 posgtgresql 5.6)是

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

like

喜欢

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

Assuming userstable has a json column named datawhich is something like:

假设users表有一个名为的 json 列data,类似于:

{"failed_login_attempts_count":"2","comment":"VIP"}

回答by Denis de Bernardy

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

to_json(1)::text::int 可能太慢了

But then, it's the only way.

但是,这是唯一的方法。

The second part of your question is unclear.

你问题的第二部分不清楚。

回答by Craig Ringer

The PostgreSQL 9.3 JSON support is simply validated json text.

PostgreSQL 9.3 JSON 支持只是经过验证的 json 文本。

In 9.4 and newer you can use jsonb.

在 9.4 及更新版本中,您可以使用 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 notbe too slow, i.e. what do you expect?

“可能太慢了”没有多大意义。是什么让你觉得它太慢了?您是否进行了测试和基准测试?如果它“太慢”什么速度不会太慢,即你期望什么?