简体   繁体   中英

Put variable inside json_extract_path_text in postgresql query

I have following select:

select json_extract_path_text(rules, 'amount', '5', 'percentage')
from promotion_rules

Sample from JSON looks like this:

{
    "amount": {

        "1": {
            "percentage": 1
        },
        "2": {
            "percentage": 3
        },
        "3": {
            "percentage_below_eq": 5,
            "percentage_above": 10,
            "price": 20
        },
        "4": {
            "percentage_below_eq": 10,
            "percentage_above": 15,
            "price": 20
        }
    }
}

I want to use values from other queries/tables/cte inside above json_extract function instead of '5' (or achieve exact effect), how it can be done?

Here's the part of code and fiddle with full data, I can't put it all here because stack tells me that my post i mostly code.

with percentages as (select pr.*, json_object_keys(rules->'amount')::INT as amount
from
promotion_rules pr
where id = 1
)
select
o.id as order_id,
json_extract_path_text(rules, 'amount', o.products_no, 'percentage') as percentage --it doesn't work this way, either with brackets
from orders o
join percentages p on p.amount = o.products_no

https://www.db-fiddle.com/f/oSQ3eW2G3kHgr3xvpHLw9Q/0

json_extract_path expects a list of text parameters.

If you want to use a column that's not text you need to cast it:

json_extract_path_text(rules, 'amount', , 'percentage')

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