Given the following JSON (or JSONB) object:
{"apple": 13.1, "banana": 2.0, "zucchini": 7.2, "orange": 19.1}
I would like to sort the object keys by their values and get this instead:
{"banana": 2.0, "zucchini": 7.2, "apple": 13.1, "orange": 19.1}
How do I do that using PostgreSQL 14 and its JSON/JSON-B features?
Type
jsoncan hold an arbitrary order of keys butjsonbdeduplicates and reorders the keys internally. That means you will needjsonand you will need to construct it based on a reorderedjson(b)_each_text()of the input value, which you need to aggregate back intojson_object_agg(), internally ordering it by values: demo at db<>fiddleI don't know your primary key, so to re-construct each json(b) value in your desired order I grouped them by system column
ctid, which I could rely on being always present and unique.