使用postgresql查询查找json数组的值

时间:2013-12-05 04:43:39

标签: json postgresql

这是我的JSON值

"order": {
        "items": [{
            "amount": 30000,
            "product_name": "product A",
            "quantity": 3,
         }, {
            "amount": 1000,
            "product_name": "product B",
            "quantity": 1,
        }],
        "currency": "USD"
    }

我希望使用mysql查询从数组中获取数量的值。我尝试选择json_extract_path_text('order','items')但它获取整个值

 [{
            "amount": 30000,
            "product_name": "product A",
            "quantity": 3,
         }, {
            "amount": 1000,
            "product_name": "product B",
            "quantity": 1,
        }]

你能帮助我吗?

1 个答案:

答案 0 :(得分:1)

您可以使用json_array_elements()功能:

select
    (value->>'amount')::int as amount
from json_array_elements(
    '{"order":
         {  "items": [
                {"amount": 30000,"product_name": "product A", "quantity": 3},
                {"amount": 1000,"product_name": "product B","quantity": 1}
            ],
            "currency": "USD"}
     }'::json->'order'->'items'
)