h2non / jsonpath-ng

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

Can I register custom functions? #111

Closed norouzzadegan closed 1 year ago

norouzzadegan commented 1 year ago

Hi, guys. I want create custom function in Jsonpath, For example I have a json alike below:

[{
    "name':'/home/user/Desktop/test.txt',
    'executable': True,
    'binary': False,'type':'file'
}]

I Want get content a file in path "/home/user/Desktop/test.txt" based on its name in json. For example the query is $.[1].content() Can I create custom function in jasonpath-ng?

1wang-wood commented 1 year ago

fork your own project add a new class in jsonpath_ng.ext.string.py which named "Content" extends jsonpath_ng.jsonpath.ext.string.This image implements find method in Content to return content of file add an elif in jsonpath_ng.ext.parser.ExtentedJsonPathParser.p_jsonpath_named_operator method like

elif p[1].startswith("content("):
            p[0] = _string.Str(p[1])

then you can use jsonpath express like this $.[1].`content()` to read content of file

michaelmior commented 1 year ago

@norouzzadegan It seems like there's a solution here, so closing this but feel free to reopen if needed.