从JSONB对象中提取具有真实值的键名 [英] Extracting key names with true values from JSONB object

查看:71
本文介绍了从JSONB对象中提取具有真实值的键名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从具有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';

我不喜欢在比较stringsWHERE子句.有没有办法将其转换为boolean?
如果是,是否也适用于truthyfalsy值? (在javascript中truthyfalsy值的解释: 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对象中提取具有真实值的键名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆