Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON Path String Evaluation of root value

Have a service that returns a very basic json respons:

{
    "methodresult": "error",
    "ErrorCode": 2,
    "ErrorCodeText": "format",
    "ErrorMessage": "Json parse exception at pos:171 msg:Expecting \"key\""
}

And am trying to use JSONPath to query if the "methodresult" value is coming back as "error".

Based on the documentation/examples I've seen I would expect this to work:

$[?(@.methodresult=="error")]

However based on validators I'm utilizing like this (https://jsonpath.curiousconcept.com/) am not seeing any boolean response.

When trying to write an expression against something not in an array is there something I'm missing?

like image 943
GAG Avatar asked Oct 25 '18 16:10

GAG


2 Answers

Include the json response within square brackets and it works.

[{
"methodresult": "error",
"ErrorCode": 2,
"ErrorCodeText": "format",
"ErrorMessage": "Json parse exception at pos:171 msg:Expecting \"key\""
}]


$[?(@.methodresult=="error")].methodresult

Result:

[  
"error"
]
like image 77
Hemanthi Avatar answered Sep 28 '22 01:09

Hemanthi


No, I don't think you are missing anything.

The problem is in the lack of a true standard for JSONPath. There are a few ideas/proposals (including a somewhat related one for JSON Pointer, which has been stuck in 'PROPOSED STANDARD' phase for years now), many implementations, and they are all different in some way even when they supposedly implement the same proposal (e.g. Stefan Goessner's one).

For example, when using Jayway JsonPath, these JSONPath expressions

$.[?(@.methodresult == 'error')]
 $[?(@.methodresult == 'error')]
 .[?(@.methodresult == 'error')]
  [?(@.methodresult == 'error')]

produce the same result for the input JSON from the question:

{
    "methodresult": "error",
    "ErrorCode": 2,
    "ErrorCodeText": "format",
    "ErrorMessage": "Json parse exception at pos:171 msg:Expecting \"key\""
}

They return a non-empty array containing the JSON object that has methodresult field equal to error. And that is to be expected if one looks at Stefan Goessner's proposal...

Trying those same expressions for the given input here (link provided in the question) or here (which offers running a given JSONPath expression using 4 different implementations), and the results will be mixed: failed parsing, execution errors, an empty array, and sometimes as expected.

The bottom line is that, until there is a true standard for JSONPath, the only way to make sure a JSONPath expression works as expected is to write it for the concrete JSONPath implementation that you will be using in your application.

like image 21
apisim Avatar answered Sep 28 '22 02:09

apisim