1

This works fine:

jsonb_path_query(p.blah::jsonb, '$[*] ? (@.fruit == "banana") ') 

but if I want to compare the JSON "fruit" property to a value from a column, I cannot get Postgres to parse it, like so:

jsonb_path_query(p.blah::jsonb, '$[*] ? (@.fruit == c.fruit) ') 

I get hard-to-understand errors like "syntax error, unexpected IDENT_P at end of jsonpath input"

2 Answers 2

3

All JSONpath functions also accept an additional JSON parameter that contains key/value pairs that can be referenced inside the JSON path expression:

jsonb_path_query(jsonb_column, 
                 '$[*] ? (@.fruit == $fp)', 
                 jsonb_build_object('fp', c.fruit) )
Sign up to request clarification or add additional context in comments.

2 Comments

Not all, jsonb_set() and jsonb_insert() being examples.
@TilmanVogel: those aren't JSON path functions (they accept a "path", but it's not a "JSONpath" value)
1

Use format() to build the second parameter, e.g.:

with my_table (fruit, json_col) as (
values
    ('banana', '[{"fruit": "banana"}, {"fruit": "apple"}]'::jsonb),
    ('apple', '[{"fruit": "pear"}]'),
    ('plum', '[{"fruit": "pear"}, {"fruit": "plum"}]')
)

select 
    fruit, 
    jsonb_path_query(json_col, format('$[*] ? (@.fruit == "%s")', fruit)::jsonpath) 
from my_table;

 fruit  |  jsonb_path_query
--------+---------------------
 banana | {"fruit": "banana"}
 plum   | {"fruit": "plum"}
(2 rows)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.