4

I need a jsonpath expression, which returns the first element of an array which has "key" property.

I'm looking for the same result as this query:

SELECT
  j
FROM
jsonb_array_elements(
    '[
      {"key": "foo"},
      {"other": "bar"},
      {"key":  "baz", "other": "blah"}
    ]'::JSONB
) j
WHERE
  j ? 'key'
LIMIT 1

My query looks like this currently, but doesn't work

SELECT
    jsonb_path_query(
      '[
        {"key": "foo"},
        {"other": "bar"},
        {"key":  "baz", "other": "blah"}
      ]'::JSONB,
      '$[?(@.key)] [0]')

1 Answer 1

2

Please see this: https://www.postgresql.org/docs/12/functions-json.html#FUNCTIONS-SQLJSON-PATH-OPERATORS

SELECT
    jsonb_path_query_first(
      '[
        {"key": "foo"},
        {"other": "bar"},
        {"key":  "baz", "other": "blah"}
      ]'::JSONB,
      '$[*] ? (exists (@.key))')
;

 jsonb_path_query_first 
------------------------
 {"key": "foo"}
(1 row)

Sign up to request clarification or add additional context in comments.

1 Comment

To help with search, if you're writing any json path query which is guaranteed to return one result (e.g. '$[0]' accessing the first position of an array), leveraging jsonb_path_query_first instead of jsonb_path_query is a great way to work around set-returning function limitations. This lets you use json path queries in WHERE clauses, window functions, etc which otherwise would break with the set return value.

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.