JSON Path String Evaluation of root value
Asked Answered
D

2

6

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?

Darfur answered 25/10, 2018 at 16:28 Comment(0)
J
5

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"
]
Joshua answered 19/11, 2018 at 11:33 Comment(0)
H
2

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.

Hamon answered 21/11, 2018 at 0:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.