I have a jsonb column such that:
| id | fee |
|----------|----------------------------------------|
| 1 | "[{"Step": "step1", "Value": "10"}]" |
| 2 | "[{"Step": "step1", "Value": "999"}]" |
| 3 | [] |
And I want to calculate the Value filed and add new property in the same fee column such that:
ROUND((Value / 1.07),2)
I tried this below code but its not working.
update plans
set excess_fees = jsonb_set(plans.excess_fees, '{0, ValueExclGst}',
(select cast(round(cast(VALUE as decimal), 2) as text)
from jsonb_array_elements(plans.excess_fees->'Value') as VALUE));
The output looks like this:
| id | fee |
|----|-----|
| 1 | "[{"Step": "step1", "Value": "10", "ValueExclGst":"9.35"}]" |
| 2 | "[{"Step": "step1", "Value": "999", "ValueExclGst": "933.64"}]" |
| 3 | [] |
How shall I do in Postgres since I am new to Jsonb?
Thank you for your time and answers.
jsonb_array_elementsandjsonb_setwould come handy for this. A working query:The query works in these phases:
Create a
fee_jsonauxiliary statement using CTE by deflating thefeearray column. Nowfee_jsonhas a columnjson_datawith all the deflated jsonb objects along with the correspondingid.Create another
updated_rowsauxiliary statement using the values fromfee_json. In this statement, we're inserting a new valueValueExclGstin the jsonb using the value fromValuefield in jsonb. We array aggregate all such jsonb objects byidusingjsonb_agg.We update the value from
udpated_rowsusing theidfield in ourplanstable.A working db-fiddle for better understanding.