Filter json properties by name using JSONPath

孤街醉人 提交于 2020-01-06 06:01:09

问题


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:


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


来源:https://stackoverflow.com/questions/52503025/filter-json-properties-by-name-using-jsonpath

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