Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Given the input JSON from the 'table' under a column named '_value'. I would like to replace the field "sc" as text from object to value of name under sc.

The json before updating looks like this.

{
    "iProps": [
    {
        "value": {
            "rules": [
                {
                    "ao": {
                        "sc": {
                            "web_link": "abc.com",
                            "name": "name"
                        }
                    }
                },
                {
                    "ao": {
                        "sc": ""
                    }
                }
            ]
        }
    }
]
}

The json after updating should look like this.

{
    "iProps": [
    {
        "value": {
            "rules": [
                {
                    "ao": {
                        "sc":  "name"
                    }
                },
                {
                    "ao": {
                        "sc": ""
                    }
                }
            ]
        }
    }
]
}

I tried the below query to get to 'rules' array but having difficulty to proceed further in parsing and updating.

 WITH values AS (
    SELECT iprop -> 'value' -> 'rules' AS value FROM
    table t,jsonb_array_elements(t._value->'iProps') AS 
        iprop )
SELECT *
from values, jsonb_array_elements(values.ao)

throws following error

ERROR:  column values.ao does not exist
LINE 26: from values, jsonb_array_elements(values.ao)
                                           ^
SQL state: 42703
Character: 1396

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
203 views
Welcome To Ask or Share your Answers For Others

1 Answer

You can try below mentioned query considering your structure is constant and the data type of your column is JSONB.

with cte as (
select 
 vals2->'ao'->'sc'->'name' as namevalue,
  ('{iProps,'||index1-1||',value,rules,'||index2-1||',ao,sc}')::text[] as json_path
from 
  table_, 
  jsonb_array_elements(value_->'iProps') 
  with ordinality arr1(vals1,index1),
  jsonb_array_elements(vals1->'value'->'rules') 
  with ordinality arr2(vals2,index2)

  )

 update table_ 
 set value_ = jsonb_set(value_,cte.json_path,cte.namevalue,false) 
 from cte
WHERE cte.namevalue IS NOT NULL

DEMO


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...