h2non / jsonpath-ng

Finally, a JSONPath implementation for Python that aims to be standard compliant. That's all. Enjoy!
Apache License 2.0
582 stars 85 forks source link

Filter a top level field #66

Open maximlt opened 3 years ago

maximlt commented 3 years ago

Given:

{
    "store": {
        "bicycle": {
            "color": "red",
            "price": 19.95
        }
    },
    "expensive": 10
}

The expressions $[?($.expensive)] (look for the root/top level expensive field) or $[?($.expensive == "10")] (check its value) both return:

[
   {
      "store" : {
         "bicycle" : {
            "color" : "red",
            "price" : 19.95
         }
      },
      "expensive" : 10
   }
]

with the Jayway JSONPath (test them on jsonpah.herokuapp.com).

The same expressions return an empty list with jsonpath-ng. Not sure whether this is a bug in jsonpath-ng or its expected behaviour (difficult to say since there's no formal JSONPATH spec).

The workaround is simple though:

import json
def filter_json_toplevel(file: filepath, field: str, val: str) -> list
    data = json.load(file)
    if data.get(field) == val:
        return [data]
    else:
        return []
languitar commented 3 years ago

Unfortunately, the "specification" for JSONPath is pretty imprecise. I just looked into how to solve this case, but if I make this one working, the previously merged semantics for https://github.com/h2non/jsonpath-ng/pull/41 do not work anymore. The specification doesn't mention anything regarding object access using [] as far as I can tell and most implementations seem to behave differently :/