使用以下 json 示例:
{
"red": false,
"blue": false,
"yellow": false
}
我必須將其中一個元素更新為 true,預期結果是:
{
"red": false,
"blue": false,
"yellow": true
}
首先,我嘗試以這種方式更新:
UPDATE table_name
SET jsonb_column_name = jsonb_set(jsonb_column_name, '{yellow}', ('"true"')::jsonb, true)
但結果是
{
"red": false,
"blue": false,
"yellow": "true"
}
不是我想要的,它是一個字串,而不是 bool
還試過:
UPDATE table_name
SET jsonb_column_name = jsonb_set(jsonb_column_name, '{yellow}', true, true)
但是我得到了一個錯誤,這是有道理的,第三個引數必須是 jsonb
SQL Error [42883]: ERROR: function jsonb_set(jsonb, unknown, boolean, boolean) does not exist
Hint: No function matches the given name and argument types. You might need to add explicit type casts.
我不能使 true::jsonb 因為 bool 不能轉換為 jsonb:
SQL Error [42846]: ERROR: cannot cast type boolean to jsonb
還有另一種方法可以做到這一點嗎?不需要使用 jsonb_set,我想我可以使用 str_replace 然后轉換為 jsonb 但我不知道它是否安全
uj5u.com熱心網友回復:
感謝 Edouard 的回答,我意識到我沒有測驗所有明顯的可能性。
'true'::jsonb 只用單引號作業
UPDATE table_name
SET jsonb_column_name = jsonb_set(jsonb_column_name, '{yellow}', 'true'::jsonb, true)
uj5u.com熱心網友回復:
你不需要jsonb_set這個例子。由于這是一jsonb列,您可以簡單地附加新值,現有的鍵/值對將替換為新的。
update table_name
set jsonb_column_name = jsonb_column_name || '{"yellow": true}';
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/341495.html
標籤:sql PostgreSQL jsonb
