使用以下 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"
}
不是我想要的,它是一个字符串,而不是布尔值
也试过:
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 但我不知道它是否安全