Re: JSONpath query that returns paths to the matches
От | Alex R |
---|---|
Тема | Re: JSONpath query that returns paths to the matches |
Дата | |
Msg-id | CANK1NR2=WvSBRAL=HKsZUHyoK_uTZKajwoE-bC=Q2GNHzSkv0g@mail.gmail.com обсуждение исходный текст |
Ответ на | Re: JSONpath query that returns paths to the matches ("David G. Johnston" <david.g.johnston@gmail.com>) |
Список | pgsql-novice |
Hi David,
Thank you for the swift reply. After ruling out the option of doing that by leveraging JSONPath, I took a different approach and wrote a function in pl/pgsql that does not need these paths at all. I could deviate a bit, because I had some wiggle room in the context of the bigger problem I was working on.
For others who might be confronted with a similar problem in the future, here is a minimal example that uses Python and a library called jsonpath_ng, which tells you what the match is and where it occurs:
```
# pip install jsonpath_ng
import json
from jsonpath_ng import jsonpath, parse
raw = '''{
"this": "that",
"that": [{"x": "aaa"},{"y": "missed"}],
"nested": {
"deep": {
"x": "bbb"
}
}
}'''
data = json.loads(raw)
query = parse('$..x')
results = query.find(data)
for entry in results:
print(f'{entry.full_path} -> {entry.value}')
# that.[0].x -> aaa
# nested.deep.x -> bbb
import json
from jsonpath_ng import jsonpath, parse
raw = '''{
"this": "that",
"that": [{"x": "aaa"},{"y": "missed"}],
"nested": {
"deep": {
"x": "bbb"
}
}
}'''
data = json.loads(raw)
query = parse('$..x')
results = query.find(data)
for entry in results:
print(f'{entry.full_path} -> {entry.value}')
# that.[0].x -> aaa
# nested.deep.x -> bbb
```
Porting this to pl/python is left as an exercise for the reader :-)
В списке pgsql-novice по дате отправления: