0

In PostgreSQL using jsonb column, is there a way to select / convert an attribute with actual datatype the datatype instead of getting it as a string object when using jsonpath? I would like to try to avoid cast as well as -> and ->> type of construct since I have to select many attributes with very deep paths, I am trying to do it using jsonpath and * or ** in the path

Is it possible to do it this way or must I use the -> and ->> for each node in the path ? This will make the query look complicated as I have to select about 35+ attributes in the select with quite deep paths.

Also, how do we remove quotes from the selected value?

This is what I was trying, but doesn't work to remove quotes from Text value and gives an error on numeric

Select 
    PolicyNumber AS "POLICYNUMBER",
    jsonb_path_query(payload, '$.**.ProdModelID')::text   AS "PRODMODELID",
    jsonb_path_query(payload, '$.**.CashOnHand')::float   AS "CASHONHAND"
from policy_json_table

the PRODMODELID still shows the quotes around the value and when I add ::float to second column, it gives an error

SQL Error [22023]: ERROR: cannot cast jsonb string to type double precision

Thank you

1 Answer 1

0

Remember that jsonb_path_query() returns jsonb objects. If you want the contents of the object (even if it is a primitive type), extract element 0. There is no support for extracting values into anything other than json(b) or text, so you will have to then convert text to whatever numeric type you need.

->>0 only works for jsonb primitives, oddly enough.

Select 
    PolicyNumber AS "POLICYNUMBER",
    jsonb_path_query(payload, '$.**.ProdModelID')->>0 AS "PRODMODELID",
    (jsonb_path_query(payload, '$.**.CashOnHand')->>0)::float AS "CASHONHAND"
from policy_json_table

Aside: Please, please, please don't use floating point for currency. Your accountants will kill you over the disappearing/reappearing pennies. Use numeric for currency values.

1
  • Thanks. I will test this and accept the answer. Also, on some site, I saw they used this construct - #>> '{}' to get the text value, not object. I have been trying to find out how it works. Any idea? Couldn't find that explained anywhere. Also, thanks for the suggestion to use numeric. The above I was just trying to get the data as non-string
    – adbdkb
    Oct 28, 2022 at 10:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.