简体   繁体   中英

Rails PSQL query JSON for nested array and objects

So I have a json (in text field) and I'm using postgresql and I need to query the field but it's nested a bit deep. Here's the format:

[
  {
    "name":"First Things",
    "items":[
      {
        "name":"Foo Bar Item 1",
        "price":"10.00"
      },
      {
        "name":"Foo Item 2",
        "price":"20.00"
      }
    ]
  },
  {
    "name":"Second Things",
    "items": [
      {
        "name":"Bar Item 3",
        "price":"15.00"
      }
    ]
  }
]

And I need to query the name INSIDE the items node. I have tried some queries but to no avail, like: .where('this_json::JSON @> [{"items": [{"name": ?}]}]', "%#{name}%") . How should I go about here?

I can query normal JSON format like this_json::JSON -> 'key' = ? but need help with this bit.

Here you need to use json_array_elements() twice, as your top level document contains array of json, than items key has array of sub documents. Sample psql query may be the following:

SELECT
  item->>'name' AS item_name,
  item->>'price' AS item_price
FROM t,
  json_array_elements(t.v) js_val,
  json_array_elements(js_val->'items') item;

where t - is the name of your table, v - name of your JSON column.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM