1

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.

index
  • 3,697
  • 7
  • 36
  • 55

1 Answers1

0

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.

Dmitry S
  • 4,990
  • 2
  • 24
  • 32