How do I create json path syntax\query that tries and find a child element, but if it can't find it falls back to the root element?
I've tried the following:
['$.form_response.definition'],$
'$.form_response.definition',$`
'$.form_response.definition','$'
'$.form_response.definition',`this`
['$.form_response.definition']|$
... (and probably a lot more that I've already forgotten about)
but unfortunately nothing seems to work correctly or it just throws errors.
I would expect that it will try and look for the form_response.definition
element and it that can't be found, it will just return the root
element.
Let's for example take the following piece of code. In one JSON the part I'm looking for is in the under response.definition
, but in the other JSON the part I'm looking for is directly at the root.
from jsonpath_ng import parse
parse('$.response.definition, $').find({'id': '123', 'response': {'id': '987', 'definition': {'title': 'hi'}}})
result = parse('$.response.definition, $').find({ 'id': '123', 'title': 'hi'})
But running this gives the following error.
raise JsonPathParserError('Parse error at %s:%s near token %s (%s)'
% (t.lineno, t.col, t.value, t.type))
jsonpath_ng.exceptions.JsonPathParserError: Parse error at 1:23 near token $ ($)
I've tried so many things by now. Is there a way to do this?