I try to remove pixelId":"AW-23423524124" from the array and in case its the only one in the array trackingIds than remove the entire object of pxg. it does not work using PostgreSQL
UPDATE clicks
SET protection_config =
CASE
WHEN protection_config LIKE '%{"pxg":{"trackingIds":[{"pixelId":"AW-23423524124"%' AND jsonb_array_length(replace(replace(protection_config, 'false', '0'), 'true', '1')::jsonb->'pxg'->'trackingIds') = 1
THEN '{}'
WHEN protection_config LIKE '%{"pxg":{"trackingIds":[{"pixelId":"AW-23423524124"%' AND jsonb_array_length(replace(replace(protection_config, 'false', '0'), 'true', '1')::jsonb->'pxg'->'trackingIds') > 1
THEN replace(replace(protection_config, 'false', '0'), 'true', '1')::jsonb #- '{pxg, trackingIds}' || jsonb_build_object('pxg', jsonb_build_object('trackingIds', (replace(replace(protection_config, 'false', '0'), 'true', '1')::jsonb->'pxg'->'trackingIds') #- '{0}' #- '{pixelId}'))::text
ELSE protection_config
END
WHERE protection_config LIKE '%{"pxg":{"trackingIds":[{"pixelId":"AW-23423524124"%' and network_id='5766'
column looks like that– please note the column is type -character varying
{"monitoringMode":{"isMonitoring":false,"dates":null},"pxg":{"trackingIds":[{"active":1,"pixelId":"AW-23423524124"}]},"uaTrackingIds":[{"pixelId":"UA-123","dimensionIndex":"dimension123"},{"pixelId":"UA-1233","dimensionIndex":"dimension3"}]}
2
Answers
You can benefit from converting the column in question to a json type. Kind of
db<>fiddle
I used almost same logic as yours.
json_array_length
to get array length.jsonb_path_query_array
used to get data as array based on condition.jsonb_set
to update our json.Docs here
Demo here
To remove the entire object
pxg
use this instead :