问题描述
我正在尝试从具有true
值的JSONB
类型中选择键.到目前为止,我设法使用此查询来做到这一点,但我觉得有更好的方法:
I'm trying to select keys from JSONB
type with true
values. So far I managed to do that using this query but I feel like there is a better way:
SELECT json.key
FROM jsonb_each_text('{"aaa": true, "bbb": false}'::JSONB) json
WHERE json.value = 'true';
我不喜欢在比较strings
的WHERE
子句.有没有办法将其转换为boolean
?
如果是,是否也适用于truthy
和falsy
值? (在javascript中truthy
和falsy
值的解释: http://www.codeproject.com/Articles/713894/Truthy-Vs-Falsy-Values-in-JavaScript ).
What I don't like is the WHERE
clause where I'm comparing strings
. Is there a way to cast it to boolean
?
If yes, would it work for truthy
and falsy
values too? (explanation of truthy
and falsy
values in javascript: http://www.codeproject.com/Articles/713894/Truthy-Vs-Falsy-Values-in-JavaScript).
推荐答案
jsonb
具有相等运算符(=
;与json
不同),因此您可以编写
jsonb
has an equality operator (=
; unlike json
), so you could write
SELECT key
FROM jsonb_each('{"aaa": true, "bbb": false}')
WHERE value = jsonb 'true'
(对于jsonb_each_text()
,您依赖某些JSON值的文本表示形式.)
(with jsonb_each_text()
you rely on some JSON values' text representation).
如果需要,您甚至可以添加一些其他值:
You can even include some additional values, if you want:
WHERE value IN (to_jsonb(TRUE), jsonb '"true"', to_jsonb('truthy'))
IN
在幕后使用等号运算符.
IN
uses the equality operator under the hood.
这篇关于从JSONB对象中提取具有真实值的键名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!