简体   繁体   中英

Accessing an Array Inside JSON with a Postgres Query

I have a table with a data_type of json that I need to query one of the properties inside of it.

This is what the data in the column looks like:

{
  "id": 7008,
  "access_links": [
    {
      "product_code": "PRODUCT-1",
      "link": "https://some.url"
    },
    {
      "product_code": "PRODUCT-2",
      "link": "https://someOther.url"
    }
  ],
  "library_id": "2d1203db-75b3-43a5-947c-8555b48371db"
}

I need to be able to pull out and filter by the product_code nested inside of the access_links .

I can get one layer deep by using this query:

SELECT
    courses.course_metadata -> 'access_links' as access_links 
FROM
    courses

This seems to get me into the column, but I can't query any further.

The output I receive from the query looks like:

[{"product_code":"PRODUCT-1","link":"https://some.url"},{"product_code":"PRODUCT-2","link":"https://someOther.url"}]

I've tried using the ->> and #>> operators, but they both complain about the array not starting with a { . Also worth noting that the column is a data type of JSON not JSONB , so the @> operator doesn't work.

What am I missing here?

Does this help?

select 
json_array_elements (x->'access_links')->'product_code' as product_code
from 
(select '{
  "id": 7008,
  "access_links": [
    {
      "product_code": "PRODUCT-1",
      "link": "https://some.url"
    },
    {
      "product_code": "PRODUCT-2",
      "link": "https://someOther.url"
    }
  ],
  "library_id": "2d1203db-75b3-43a5-947c-8555b48371db"
}'::json x 
  )  as v 
  ;

product_code

"PRODUCT-1"
"PRODUCT-2"

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