2

Using JsonPath.Net, is it possible to write a single query that will obtain the values of properties with the same key at different nesting levels?

For example, from the following JSON:

{
  "ObjA" : {
    "textValue" : "a1",
    "numValue" : 1
  },
  "ObjB" : {
    "objArray": [
      {
        "textValue": "b1",
        "numValue" : 1
      },
      {
        "textValue": "b2",
        "numValue" : 2
      }
    ]
  }
}

Can we get a list of all "textValue", i.e:

[
  "a1",
  "b1",
  "b2"
]

Or all "numValue", i.e:

[
  1,
  1,
  2
]

I have been trying to do this on https://json-everything.net/json-path/, but I can't figure out how.

1 Answer 1

2

JsonPath.Net supports the recursive descent operator ... You can use it to descend the JSON hierarchy, then pick out a particular property by adding the property name after the .. like so:

var rootJsonNode = JsonNode.Parse(jsonText);

var path = JsonPath.Parse("$..textValue");
var results = path.Evaluate(rootJsonNode);                        
var newArray = JsonSerializer.SerializeToNode(results.Matches.Select(m => m.Value))!.AsArray();

Or

var path = JsonPath.Parse("$..numValue");

Demo fiddle here.

For confirmation, see RFC 9535: JSONPath: Query Expressions for JSON :

Syntax Element Description
..[<selectors>] descendant segment (Section 2.5.2): selects zero or more descendants of a node
..name shorthand for ..['name']
..* shorthand for ..[*]
Sign up to request clarification or add additional context in comments.

1 Comment

This is a thorough explanation. I must read through the entire RFC.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.