我在JSON列中存储了一个十进制值作为字符串:
{"path": {"to": {"decimal": "123.45"}}}
我可以使用#>
运算符提取小数值:
SELECT foo #> '{path,to,decimal}'
FROM (
SELECT '{"path": {"to": {"decimal": "123.45"}}}'::json AS foo
) AS footable
但结果是 json 类型:
"123.45"
如果我将其转换为 numeric :
SELECT (foo #> '{path,to,decimal}')::numeric
FROM (
SELECT '{"path": {"to": {"decimal": "123.45"}}}'::json AS foo
) AS footable
我收到错误:
cannot cast type json to numeric
如果我将其转换为 text 然后 numeric :
SELECT (foo #> '{path,to,decimal}')::text::numeric
FROM (
SELECT '{"path": {"to": {"decimal": "123.45"}}}'::json AS foo
) AS footable
text 字符串被引用,无法转换为数字:
invalid input syntax for type numeric: ""123.45""
从 json 结构中提取值并以非 json 类型获取值的正确方法是什么?
答案 0 :(得分:10)
这是我的解决方案:
SELECT (foo #>> '{path,to,decimal}')::numeric
FROM (
SELECT '{"path": {"to": {"decimal": "123.45"}}}'::json AS foo
) AS footable
请注意#>>
operator将值检索为text
(并避免任何奇怪的隐式转换)。