Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract JSON string and cast to decimal

I have a decimal value stored as a string in a JSON column:

{"path": {"to": {"decimal": "123.45"}}}

I can extract the decimal value using the #> operator:

SELECT foo #> '{path,to,decimal}'
FROM (
    SELECT '{"path": {"to": {"decimal": "123.45"}}}'::json AS foo
) AS footable

But the result is a json type:

"123.45"

If I cast it to numeric:

SELECT (foo #> '{path,to,decimal}')::numeric
FROM (
    SELECT '{"path": {"to": {"decimal": "123.45"}}}'::json AS foo
) AS footable

I get the error:

cannot cast type json to numeric

If I cast it to text and then numeric:

SELECT (foo #> '{path,to,decimal}')::text::numeric
FROM (
    SELECT '{"path": {"to": {"decimal": "123.45"}}}'::json AS foo
) AS footable

The text string gets quoted which fails to cast to numeric:

invalid input syntax for type numeric: ""123.45""

What is the proper way to extract a value from a json structure, and get the value as a non-json type?

like image 865
Uyghur Lives Matter Avatar asked Dec 12 '22 02:12

Uyghur Lives Matter


1 Answers

Here is my solution:

SELECT (foo #>> '{path,to,decimal}')::numeric
FROM (
    SELECT '{"path": {"to": {"decimal": "123.45"}}}'::json AS foo
) AS footable

Notice the #>> operator to retrieve the value as text (and avoid any weird implicit casting).

Here is the SQLFiddle.

like image 174
Clément Prévost Avatar answered Dec 23 '22 07:12

Clément Prévost