16

The set up is ruby on rails, in a postgres database. The table is called line_sources and a JSON column is called names. I want to return all rows where the names column contains a key called away_names. I'm trying this but they fail:

LineSource.where("names -> 'away_names'")

and

LineSource.where("names ->> 'away_names' = '%'")
appleLover
  • 14,835
  • 9
  • 33
  • 50

2 Answers2

31

Try this :

where("(names->'away_names') is not null")
Nicolas Maloeuvre
  • 3,069
  • 24
  • 42
5

You can use #> to get the JSON object at that path.

where("(names #>'{away_names}') is not null")

Basic key operators to query the JSON objects :

  • #> : Get the JSON object at that path
  • ->> : Get the JSON object at that path as text
  • {obj, n} : Get the nth item in that object
pramod
  • 2,258
  • 1
  • 17
  • 22