如何在SelectToken JSONPath查询中的运行时使用字符串值

问题描述 投票:0回答:1

我有以下代码,我在C#中使用流行的Newtonsoft库

string json = {
  "students": [
    {
      "name": "student 1",
      "grades": [
        {
          "subject1": "A",
          "subject2": "B"
        }
      ]
    }
  ]
}

JObject rootJObject = JObject.Parse(json);

我想选择一个特定的学生对象。如果我使用下面的文字字符串查询JSONPath,我得到的是实际的对象

rootJObject.SelectToken("$.students[?(@.name=='student 1')]");

现在如果我想在运行时传递查询字符串,如下所示

string studentName = "student 1"; rootJObject.SelectToken($"$.students[?(@.name=={studentName})]");

它正在抛出像"Unexpected character while parsing path query: s"这样的例外

是否限制我们只能在JSONPath查询中使用单引号的文字字符串而不是运行时的字符串值?

c# json.net jsonpath
1个回答
1
投票

Querying JSON with JSONPath所示,您需要在过滤器表达式中将单引号括在字符串文字周围。所以{studentName}应该是'{studentName}'

var result = rootJObject.SelectToken($"$.students[?(@.name=='{studentName}')]");

或者,使用旧的string.Format()风格:

var result = rootJObject.SelectToken(string.Format("$.students[?(@.name=='{0}')]", studentName));

或者使用简单的字符串连接:

var result2 = rootJObject.SelectToken("$.students[?(@.name=='" + studentName + "')]");

请注意,“字符串文字”并不表示“完全在编译时构造的字符串”,它表示“字符串值包含在JSONPath表达式中”。可以传入由任何方法构造的任何c#字符串。在上面的每个语句中,通过用单引号包围studentName变量的值并将其嵌入完整的JSONPath表达式,在运行时构造字符串。第一个语句使用string interpolation而第二个语句使用显式函数调用,但两者都做同样的事情。

样本.Net fiddle

© www.soinside.com 2019 - 2024. All rights reserved.