代码之家  ›  专栏  ›  技术社区  ›  Rajaraman Subramanian

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

  •  0
  • Rajaraman Subramanian  · 技术社区  · 7 年前

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

    1 回复  |  直到 7 年前
        1
  •  2
  •   dbc    7 年前

    如所示 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 .