使用JSONPath按名称过滤json属性 [英] Filter json properties by name using JSONPath

查看:1068
本文介绍了使用JSONPath按名称过滤json属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想选择属性名称中具有特定匹配项的所有元素.

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

例如,此json中所有名称以'pass'开头的属性:

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"
]

我不想按值过滤,而只按属性名称过滤.可以使用jsonpath吗?

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

我正在使用Newtonsoft.Json.Linq的方法SelectTokens(string path)

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

推荐答案

,JSONPath定义了遍历JSON文档以到达JSON子集的表达式.如果您不知道确切的属性名称,则无法使用它.

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.

在您的情况下,您需要名称以特定关键字开头的属性值.为此,您需要遍历整个JSON文本并查找以 pass 开头且具有字符串类型

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

这篇关于使用JSONPath按名称过滤json属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆