How to select JToken based on multiple name candidates in JSONPath?

社会主义新天地 提交于 2019-12-11 23:16:26

问题


I have a JObject like this:

{
  name1: {
    value [
    ...
    ]
  }
}

It may also be in the form of:

{
  name2: {
    value [
    ...
    ]
  }
}

So I'm trying to use a single JSONPath to select the JArray value out. Is there a way to do something like this?

$['name1' or 'name2']['value']

回答1:


Based on the answers to these two SO questions: OR operator in JSONPath? and JsonPath AND Operator on Array, it seems AND and OR operators are not fully supported in JSONPath yet.

However, we can use the union operator to approximate what we need. Based on the JSONPath documentation,

Union operator in XPath results in a combination of node sets.
JSONPath allows alternate names or array indices as a set.

This seems to be what we need but still, JsonPath AND Operator on Array mentioned the union operator may have some bugs or subtle differences between different implementations.

Similary, I've performed my own verification here: http://jsonpath.herokuapp.com/.

I've tried ['name1','name2']['value'] and all but Nebhale's implementation correctly parses what I need. So I guess there is a solution to my original problem but it is a bit implementation-specific so please fully test your own code first to make sure this JSONPath and union operator will work in your code base.



来源:https://stackoverflow.com/questions/35641824/how-to-select-jtoken-based-on-multiple-name-candidates-in-jsonpath

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!