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

How to use a string value in run time in SelectToken JSONPath query

我有以下代码,我在 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 查询中只能使用带有单引号的文字字符串,而不能在 运行 时间内使用字符串值,这是一种限制吗?

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 + "')]");

请注意,"string literal" 并不意味着 "a string constructed entirely at compile time",它意味着“字符串值包含在 JSONPath expression." Any c# string constructed by any method can be passed in. In each statement above a string is being constructed in run-time by surrounding the value of the studentName variable with single quotes and embedding it in a full JSONPath expression. The first statement uses string interpolation 中,而第二个使用显式函数调用,但两者做同样的事情。

示例 .Net fiddle.