Possible to search case-insensitive with JSONPath?

前端 未结 3 1227
清歌不尽
清歌不尽 2021-02-15 12:35

Using the SelectToken method of JSON.NET to select a token with JSONPath, I found no way to specifiy that the search should be case-insensitive.

E.g.

jso         


        
3条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-15 13:30

    It's really surprising that Newtonsoft gets away without supporting this. I had to write a custom JToken extension to support this. I did not need the entire JSONPath, needed just a few basic path queries. Below is the code I used

    public static JToken GetPropertyFromPath(this JToken token, string path)
    {
        if (token == null)
        {
            return null;
        }
        string[] pathParts = path.Split(".");
        JToken current = token;
        foreach (string part in pathParts)
        {
            current = current.GetProperty(part);
            if (current == null)
            {
                return null;
            }
        }
        return current;
    }
    
    public static JToken GetProperty(this JToken token, string name)
    {
        if (token == null)
        {
            return null;
        }
        var obj = token as JObject;
        JToken match;
        if (obj.TryGetValue(name, StringComparison.OrdinalIgnoreCase, out match))
        {
            return match;
        }
        return null;
    }
    

    With the above code I can parse JSON as follows

    var obj = JObject.Parse(someJson);
    JToken tok1 = obj.GetPropertyFromPath("l1.l2.l3.name"); // No $, or other json path cliché
    JToken tok2 = obj.GetProperty("name");
    string name = obj.StringValue("name"); // Code in the link below
    

    Code to entire extension available here

提交回复
热议问题