Skip to content

Conditionally return target JSON root value  #50

Closed

Description

@jg-rp

An empty JSONPath query (non-standard) or a query containing just the root identifier ($) will return the target JSON document in its entirety.

from jsonpath import findall

rv = findall("$", {'a': [1, 2, 3], 'b': 42})
print(rv)  # [{'a': [1, 2, 3], 'b': 42}]

But there is no way to conditionally return the target root (or an empty result/node list) using a filter selector. This is a known limitation in the IETF JSONPath Base. See ietf-wg-jsonpath/draft-ietf-jsonpath-base#390.

We can stray into Python and use jsonpath.match().

from jsonpath import match

data = {'a': [1, 2, 3], 'b': 42}
rv = [data] if match("$[@ < 50]", data) else []
# ...

But that is not great or always an option.

One solution is to add an additional root identifier. A root Identifier that is functionally equivalent to wrapping the target JSON value in a single-element array. I suggest the circumflex (U+005E ^ aka caret) character for this purpose. I've been calling this the "fake root identifier".

from jsonpath import findall

data = {'a': [1, 2, 3], 'b': 42}

# Implicitly wrap `data` in an array.
findall("^[[email protected] < 50]", data)  # [{'a': [1, 2, 3], 'b': 42}]
findall("^[[email protected] > 50]", data)  # []

# Same as explicitly wrapping `data`.
findall("$[[email protected] < 50]", [data])  # [{'a': [1, 2, 3], 'b': 42}]
findall("$[[email protected] > 50]", [data])  # []

Activity

  1. added
    enhancement
    on Feb 19, 2024
  2. jg-rp commented on Feb 23, 2024

    @jg-rp
    OwnerAuthor

    Closed by #51.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    JSONPathenhancement

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions