我有一個簡單的json資料,我想在其中添加另一個key:value。
select elem, position
from jsonb_all_testing,jsonb_array_elements(jsonb_col->/span>'UserProfile'/span>) with ordinality arr(elem,position)
where col1=2
輸出結果是
{"ProfileName": "WalletCustomer"} 1
{"UserBand": "MEDIUM", "ProfileName": "PMAdmin"} 2
{"ProfileName": "CorporateAdmin"} 3
現在,我想為元素2添加另一個KEY:VALUE。添加后,它應該看起來像
{"UserBand": "MEDIUM", "ProfileName": "PMAdmin", "OneMoreKey": "NewValue"}
但是我想動態地傳遞位置 "2"(實際上是2-1),因為我不知道該在哪里添加。
所以我希望能夠做這樣的事情
with t as(select elem, position
from jsonb_all_testing,jsonb_array_elements(jsonb_col->/span>'UserProfile'/span>) with ordinality arr(elem,position)
where col1=2 and elem->。 >'ProfileName'='PMAdmin')
update jsonb_all_testing
set jsonb_col=jsonb_set(jsonb_col,'{UserProfile,**t.position-1,**""OneMoreKey"}'/span>,'"NewValue"'/span>)
where col1=2;
但是這并不奏效。我已經明確地將陣列的位置設定為數字1。
我怎樣才能實作這一點并動態地設定數值呢?
uj5u.com熱心網友回復:
是的,當然,這種瘋狂的語法是行不通的。你必須從你的CTE中選擇,你不能只是把它當作一個變數來參考。 另外,你應該使用陣列建構式ARRAY[...]構造你的陣列,而不是作為一個單一的字串。 你可以用連接法把它組裝成字串,但這更難閱讀,也更容易出錯。
...
update jsonb_all_testing
set jsonb_col=jsonb_set(jsonb_col,ARRAY['UserProfile', (SELECT position-1 FROM t)。) :text,'OneMoreKey'],'"NewValue")
where col1=2;
uj5u.com熱心網友回復:
除了@jjanes所建議的具有正確語法的CTE之外,還有一個替代方法就是
UPDATE jsonb_all_testing
SET jsonb_col = jsonb_set(jsonb_col, '{UserProfile}'/span>, (
SELECT jsonb_agg(
CASE elem->>'ProfileName'/span>
WHEN 'PMAdmin' THEN elem || '{"OneMoreKey": "NewValue"}'
ELSE elem
END
)
FROM jsonb_array_elements(jsonb_col->'UserProfile'/span>)
)
WHERE col1=2;
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/322802.html
標籤:
上一篇:查找json物件中的出現次數
