0

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';

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).

icl7126
  • 5,740
  • 4
  • 53
  • 51
  • `jsonb` has an equality operator (`=`; unlike `json`), so you could write `FROM jsonb_each(...) json WHERE json.value = jsonb 'true'` (with `jsonb_each_text()` you rely on some JSON values' text representation). – pozs Jan 21 '16 at 16:46

1 Answers1

2

jsonb has an equality operator (=; unlike json), so you could write

SELECT key
FROM   jsonb_each('{"aaa": true, "bbb": false}')
WHERE  value = jsonb 'true'

(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 uses the equality operator under the hood.

pozs
  • 34,608
  • 5
  • 57
  • 63