Skip to content

Retrieve values from the last object in a JSON object in Postgres

I have a Postgres table that has a field, KPI, containing a JSON object. It contains data for every week of the year. I want to return the values contained for the current week, in this case w5 which is always the last item in the JSON.

Extract from KPI field

This is the SQL I have

And I get the following error message:

I’m trying to get this result.

Advertisement

Answer

If you want to get always the last entry (not the specific w5 element):

In fact, there is no guarantee for a specific order of elements in a JSON object. If you want to risk that, this could be a solution:

  1. Expand the JSON elements into one record per element. Add an index to be able to sort them in next step
  2. Order “last” (see notice above!) element to top and limit output to one to return only the “last” record
  3. Return the values.
User contributions licensed under: CC BY-SA
9 People found this is helpful