Alpha75
Alpha75

Reputation: 2280

Filter json properties by name using JSONPath

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

Upvotes: 2

Views: 1865

Answers (1)

Tushar Kaurani
Tushar Kaurani

Reputation: 56

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));
}

Upvotes: 4

Related Questions