How to select JToken based on multiple name candid

2019-09-03 01:29发布

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条回答
我只想做你的唯一
2楼-- · 2019-09-03 02:10

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.

查看更多
登录 后发表回答