2

I'd like to select all elements with a certain match in the name of the property.

For example, all the properties whose name starts with 'pass' from this json:

{
  "firstName": "John",
  "lastName" : "doe",
  "age"      : 50,
  "password" : "1234",
  "phoneNumbers": [
    {
      "type"  : "iPhone",
      "number": "0123-4567-8888",
      "password": "abcd"
    },
    {
      "type"  : "home",
      "number": "0123-4567-8910",
      "password": "fghi"
    }
  ]
}

Would result something like this:

[
  "1234",
  "abcd",
  "fghi"
]

I don't want filter by values, only by property names. Is it possible using jsonpath?

I'm using the method SelectTokens(string path) of Newtonsoft.Json.Linq

1
  • 1
    Looks like not, root.SelectTokens("..pass*") doesn't work, see dotnetfiddle.net/3vJl8y. Closest I can find is the array slice operator root.SelectTokens("..['password','pass']"), see dotnetfiddle.net/QozjnQ. Otherwise you could use DescendantsAndSelf() as shown here or here. Commented Sep 25, 2018 at 22:55

1 Answer 1

4

No, JSONPath defines expressions to traverse through a JSON document to reach to a subset of the JSON. It cannot be used when you don't know the exact property names.

In your case you need property values whose name starts with a specific keyword. For that, you need to traverse the whole JSON text and look for the property names which start with pass having a string type

var passwordList = new List<string>(); 
using (var reader = new JsonTextReader(new StringReader(jsonText)))
{
    while (reader.Read())
    {
        if(reader.TokenType.ToString().Equals("PropertyName") 
           && reader.ValueType.ToString().Equals("System.String")
           && reader.Value.ToString().StartsWith("pass"))
        {
            reader.Read();
            passwordList.Add(reader.Value.ToString());
        }
    }
    passwordList.ForEach(i => Console.Write("{0}\n", i));
}
Sign up to request clarification or add additional context in comments.

1 Comment

I'd implemented a solution with dynamic variables but this seems to be more effective.

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.