Skip to content
Advertisement

postgres jsonb update key value in array

I have a table with a jsonb column with data from one row like

I want to update c_id in the table wherever it is 719 to 720. How can I do it?

I am using Postgres 12.1

Advertisement

Answer

If it is only one single occurrence, you could do it using a Regular Expression:

Click: demo:db<>fiddle

RegExp Groups:

  1. (.*) All characters before the relevant key
  2. ("c_id"s*:s*) The relevant key incl. possible spaces
  3. (719) The relevant value to be replaced
  4. (.*) Everything after the relevant point

With 127204 you put the first two groups together, followed by the new value (instead of group 3) and the fourth group.


Disclaimer:

I fully agree with @a_horse_with_no_name: You should think about storing all values in separate and normalized tables/columns. You would gain a lot of benefits (much better search and update handling, indexing, performance, …). If you need this JSON output, just handle it as output: Generate it when you need it, do not store it. Maybe a view could help a lot

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement