0

Here is my JSON field where has multiple users with the same name. I want to update all users whose name is Devang to Dev

JSON

{
    "user": [
        {
            "user_name": "Devang",
            "user_weight": 0.7676846955248864
        },
        {
            "user_name": "Meet",
            "user_weight": 0.07447325861051013
        },
        {
            "user_name": "Devang",
            "user_weight": 0.056163873153859706
        }
    ],
    "address": [
        {
            "address_name": "India"
        }
    ]
}

After Update The JSON would be

{
    "user": [
        {
            "user_name": "Dev",
            "user_weight": 0.7676846955248864
        },
        {
            "user_name": "Meet",
            "user_weight": 0.07447325861051013
        },
        {
            "user_name": "Dev",
            "user_weight": 0.056163873153859706
        }
    ],
    "address": [
        {
            "address_name": "India"
        }
    ]
}

Here I have tried this query but update only the first occurrence due to subquery.

with cte as (
  select  id,  ('{user,'||index-1||',user_name}')::text[] as json_path
  from user_table, jsonb_array_elements(json_field->'user') 
  with ordinality arr(vals,index) where arr.vals->>'user_name' ='Devang'
  )

 update user_table 
set json_field = jsonb_set(json_field,cte.json_path,'"Dev"',false) 
 from cte where user_table.id=cte.id;

Please also look at this DEMO

Any answer will be appreciated

1
  • This would be so much easier with a properly normalized data model. Commented Aug 4, 2021 at 6:05

1 Answer 1

1

You may use string function REPLACE:

UPDATE user_table
SET json_field = REPLACE(json_field :: TEXT, '"user_name": "Devang"', '"user_name": "Dev"') :: JSONB;

https://dbfiddle.uk/?rdbms=postgres_10&fiddle=fa36275977f85a1233bcbec150ada266

Sign up to request clarification or add additional context in comments.

2 Comments

what if I want to remove those object whose user_name is devang
Abandon JSONB altogether and use normalized structure with a couple of tables joined by foreign keys. Then the operations you need will be very simple.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.