I am currently working with postgreSQL 9.5 and am trying to update a value inside a jsonb field array. But I can not get the index of the selected value
My table looks simple:
CREATE TABLE samples ( id serial, sample jsonb );
My JSON looks like this:
{"result": [ {"8410": "ABNDAT", "8411": "Abnahmedatum"}, {"8410": "ABNZIT", "8411": "Abnahmezeit"}, {"8410": "FERR_R", "8411": "Ferritin"} ]}
My SELECT statement to get the correct value works:
SELECT id, value FROM samples s, jsonb_array_elements(s.sample
leads to:
id | value ---------------------------------------------- 26 | {"8410": "FERR_R", "8411": "Ferritin"}
Ok, this is what I wanted. Now I want to upgrade using the following UPDATE statement to add a new "ratingtext" element (if it does not already exist):
UPDATE samples s SET sample = jsonb_set(sample, '{result,2,ratingtext}', '"Some individual text"'::jsonb, true) WHERE s.id = 26;
After executing the UPDATE statement, my data looks like this (also correct):
{"result": [ {"8410": "ABNDAT", "8411": "Abnahmedatum"}, {"8410": "ABNZIT", "8411": "Abnahmezeit"}, {"8410": "FERR_R", "8411": "Ferritin", "ratingtext": "Some individual text"} ]}
So far, so good, but I manually searched for the value of index 2 to get the right element inside the JSON array. If the order is changed, this will not work.
So my problem is:
Is there a way to get the index of the selected element of the JSON array and combine the SELECT statement and the UPDATE statement into one?
As well as:
UPDATE samples s SET sample = jsonb_set(sample, '{result,' || INDEX OF ELEMENT || ',ratingtext}', '"Some individual text"'::jsonb, true) WHERE s.id = 26;
The values โโof samples.id and "8410" are known before preparing the statement.
Or is it impossible at the moment?