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

Readme examples do not cover update and filter #44

Closed baynes closed 1 year ago

baynes commented 4 years ago

The examples in the READMEdo not cover the update and filter functions. There is no documentation on these leading to puzzles as how to use them - see #42 - and many readers may not even realize the functionality is even there. I propose the following is added:

# Modifying values matching path
>>> jsonpath_expr.update( {'foo': [{'baz': 1}, {'baz': 2}]}, 3)
{'foo': [{'baz': 3}, {'baz': 3}]}

# Modifying one of the values matching path
>>> matches = jsonpath_expr.find({'foo': [{'baz': 1}, {'baz': 2}]})
>>> matches[0].full_path.update( {'foo': [{'baz': 1}, {'baz': 2}]}, 3)
{'foo': [{'baz': 3}, {'baz': 2}]}

# Removing all values matching path
>>> jsonpath_expr.filter(lambda d: True, {'foo': [{'baz': 1}, {'baz': 2}]})
{'foo': [{}, {}]}

# Removing values containing particular data matching path
>>> jsonpath_expr.filter(lambda d: d == 2, {'foo': [{'baz': 1}, {'baz': 2}]})
{'foo': [{'baz': 1}, {}]}
WilliamYuhangLee commented 4 years ago

The filter() function does not work when there is a filter expression in the jsonpath, and it throws a NotImplementedError. Code to duplicate this error:

obj = {
    "a": [
        {"b": "X"},
        {"b": "Y"}
    ]
}

jsonpath = parse("$.a[?(@.b==X)]")

matches = jsonpath.find(obj)
print(matches[0].value)
>>> {'b': 'X'}  # find() returns correct value

result = jsonpath.filter(lambda x: True, obj)
>>> NotImplementedError  # filter() throws error
baynes commented 4 years ago

The filter() function does not work when there is a filter expression in the jsonpath, and it throws a NotImplementedError. Code to duplicate this error:

obj = {
    "a": [
        {"b": "X"},
        {"b": "Y"}
    ]
}

jsonpath = parse("$.a[?(@.b==X)]")

matches = jsonpath.find(obj)
print(matches[0].value)
>>> {'b': 'X'}  # find() returns correct value

result = jsonpath.filter(lambda x: True, obj)
>>> NotImplementedError  # filter() throws error

@WilliamYuhangLee: I think what you have found is an interaction between the use of filter member function and the filter extensions to JSONPath. I don't think it affects my proposed documentation additions above. I suggest you raise what you have found as a separate issue.

michaelmior commented 1 year ago

@baynes I added these examples. Thanks!