How to convert strings extracted from JSON to a numeric type for aggregates?

All we need is an easy explanation of the problem, so here it is.

I am struggling to extract data from this JSON object in PostgreSQL:

"temperature": {
"boiler_temp": {
  "values": [
    "1",
    "2",
    "3",
    "3",
    "5",
    "5",
    "5",
    "5",
    "5",
    "5",
    "5",
    "5",
    "5",
    "5",
    "5",
    "5",
    "5",
    "6",
    "6",
    "6",
    "4",
    "7",
    "7",
    "7",
    "7",
    "4",
    null,
    "4",
    "5",
    "5",
    "5",
    "6",
    "6",
    "6",
    "6",
    "6",
    "6",
    "6",
    "6",
    "6",
    "5",
    "5",
    "5",
    "5",
    "5",
    "5",
    "5",
    "5",
    "2",
    "2"
  ]
}
}

I am using jsonb_array_elements() to extract it but they are returned as a string like ‘1’, ‘2’ and so on and so forth. My goal is to try and find the "avg": 5,"max": 7,"min": 1 for this data set however because I am returning them as string I am getting a value of null and an error:

My current code:

(select MIN(x::text::int) from jsonb_array_elements((data#>>'{temperature,boiler_temp}')::jsonb->'values') AS x) as mininum_temp

And I am getting an error:

ERROR: Invalid Syntax for integer :""1""

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

You need to extract them as text using jsonb_array_elements_text(), then you can cast it to an integer:

select min(x.val::int), max(x.val::int), avg(x.val::int)
from the_table
  cross join jsonb_array_elements_text(data #> '{temperature,boiler_temp,values}') as x(val)

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply