使用以下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.
和i不能使true::jsonb,因为bool不能强制转换为jsonb:
SQL Error [42846]: ERROR: cannot cast type boolean to jsonb
还有别的方法吗?不需要使用jsonb_set,我想我可以使用str_replace然后转换为jsonb但我不知道它是否安全
本例不需要jsonb_set
。由于这是一个jsonb
列,您可以简单地附加新值,现有的键/值对将被新的键/值对替换。
update table_name
set jsonb_column_name = jsonb_column_name || '{"yellow": true}';
多亏了爱德华的回答,我才意识到我并没有测试所有明显的可能性。
'true'::jsonb
与单引号工作
UPDATE table_name
SET jsonb_column_name = jsonb_set(jsonb_column_name, '{yellow}', 'true'::jsonb, true)