6

有一个返回非常基本的 json 响应的服务:

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

我正在尝试使用 JSONPath 来查询“methodresult”值是否作为“错误”返回。

根据我看到的文档/示例,我希望这可以工作:

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

但是,基于我这样使用的验证器(https://jsonpath.curiousconcept.com/)没有看到任何布尔响应。

当试图针对不在数组中的东西编写表达式时,我是否缺少某些东西?

4

2 回答 2

5

将 json 响应包含在方括号中,它可以工作。

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


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

结果:

[  
"error"
]
于 2018-11-19T11:33:41.520 回答
1

不,我不认为你缺少任何东西。

问题在于 JSONPath 缺乏真正的标准。有一些想法/建议(包括一个与JSON Pointer有点相关的想法/建议,它多年来一直停留在“提议的标准”阶段),许多实现,即使它们应该实现相同,它们在某种程度上都是不同的提案(例如Stefan Goessner 的提案)。

例如,当使用Jayway JsonPath时,这些 JSONPath 表达式

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

为来自问题的输入 JSON 产生相同的结果:

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

它们返回一个非空数组,其中包含methodresult字段等于的 JSON 对象error。如果有人看一下 Stefan Goessner 的提议,这是可以预料的……

在此处(问题中提供的链接)或此处(提供使用 4 种不同实现运行给定的 JSONPath 表达式)对给定输入尝试相同的表达式,结果将是混合的:解析失败、执行错误、空数组和有时如预期的那样。

底线是,在 JSONPath 有一个真正的标准之前,确保 JSONPath 表达式按预期工作的唯一方法是为您将在应用程序中使用的具体JSONPath 实现编写它。

于 2018-11-21T00:03:16.083 回答