如何将 PostgreSQL 9.4 的 jsonb 类型转换为 float [英] How to convert PostgreSQL 9.4's jsonb type to float
问题描述
我正在尝试以下查询:
SELECT (json_data->'position'->'lat') + 1.0 AS lat FROM updates LIMIT 5;
(+1.0 只是为了强制转换为浮动.我的实际查询要复杂得多,这个查询只是问题的一个测试用例.)
(The +1.0 is just there to force conversion to float. My actual queries are far more complex, this query is just a test case for the problem.)
我收到错误:
ERROR: operator does not exist: jsonb + numeric
如果我添加显式转换:
SELECT (json_data->'position'->'lat')::float + 1.0 AS lat FROM updates LIMIT 5;
错误变为:
ERROR: operator does not exist: jsonb + double precesion
我知道大多数 jsonb 值不能转换为浮点数,但在这种情况下,我知道 lats 都是 JSON 数字.
I understand that most jsonb values cannot be cast into floats, but in this case I know that the lats are all JSON numbers.
是否有一个函数可以将 jsonb 值转换为浮点数(或为不可转换的返回 NULL)?
Is there a function which casts jsonb values to floats (or return NULLs for the uncastable)?
推荐答案
有两种操作可以从 JSON
获取值.第一个 ->
将返回 JSON
.第二个 ->>
将返回文本.
There are two operations to get value from JSON
. The first one ->
will return JSON
. The second one ->>
will return text.
详细信息:JSON 函数和运算符
试试
SELECT (json_data->'position'->>'lat')::float + 1.0 AS lat
FROM updates
LIMIT 5
这篇关于如何将 PostgreSQL 9.4 的 jsonb 类型转换为 float的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!