Query JArray using SelectTokens and a contains regex

c# json selecttoken example
jarray selecttoken
jpath expression
jtoken
jtoken example
jobject
querying json with linq
jpath c#

I am trying to write a method that will take the following JSON structure below and return the path proerty for all of these where path contains a string. So in this case, if I called GetPath(json, "User1") I would like to get ["User1\path1", "User1\path2"]

[  
   {  
      "id":90BCV,
      "name":"Path 1",
      "path":"User1\\path 1"
   },
   {  
      "id":90BC,
      "name":"Path 2",
      "path":"User1\\path 2"
   },
   {  
      "id":91AB,
      "name":"Path 3",
      "path":"User2\\path 3"
   }
]

    public static List<string> GetPath(string json, string key)
       {
           JArray reader = JArray.Parse(json);

           List<JToken> paths = reader.SelectTokens("$.[?(@.path=~@'" + key + "')]").ToList();
           List<string> returnList = new List<string>();

           foreach (JToken path in paths)
           {
                returnList.Add((string)path["path"]);
           }

                return returnList;
}

I have tried multiple different regex approaches but I just can not seem to get this query right. Most of the times I just end up getting an empty list or an invalid regex error.

I don't know why you would want to go with this approach. I would rather use .ToString() and then use .Contains inside the foreach loop.

JArray reader = JArray.Parse(json);
List<string> returnList = new List<string>();
foreach(var token in reader){
    string path = token["path"].ToString();
    if(path.Contains(key)){
        returnList.Add(path);
    }
}

JToken.SelectToken with regex for finding values that match a pattern?, I'm not sure if this is documented anywhere (I didn't find at least), but actually in last versions (starting with 11.0.1 it seems) it does. Syntax is� This sample loads JSON and then queries values from it using M:Newtonsoft.Json.Linq.JToken.SelectToken(System.String) with a regex JSON Path.

That works

    static string json = @"
[  
   {  
      ""id"":""90BCV"",
      ""name"":""Path 1"",
      ""path"":""User1\\path 1""
   },
   {  
      ""id"":""90BC"",
      ""name"":""Path 2"",
      ""path"":""User1path 2""
   },
   {  
      ""id"":""91AB"",
      ""name"":""Path 3"",
      ""path"":""User2\\path 3""
   }
]
";
    static void Main(string[] args)
    {
      string key = "User2\\\\path 3";

      JArray reader = JArray.Parse(json);

      List<JToken> paths = reader.SelectTokens("$.[?(@.path=='" + key + "')]").ToList();

    }

few thing are there - ==, not just =, cause JPath uses in-code compiler, so you follow C# convension. - for the same reason, it you need \\ to represent \

Querying JSON with SelectToken, SelectToken makes dynamic queries easy because the entire query is defined in a string. SelectToken; SelectToken with JSONPath; SelectToken with LINQ. 1 Query JArray using SelectTokens and a contains regex Feb 25 '19. 1 jQuery: loop to change image issue Feb 26 '19. View all questions and answers → Badges (12)

By the way, if you really want to do Regular Expression way, you almost had it right:

List<JToken> paths = reader.SelectTokens("$.[?(@.path=~/^" + key + "$/)]").ToList();

Querying JSON with complex JSON Path, This sample loads JSON and then queries values from it using M:Newtonsoft. Json.Linq.JToken.SelectToken(System.String) with a� This sample loads JSON and then queries values from it using M:Newtonsoft.Json.Linq.JToken.SelectToken(System.String).

Querying JSON with JSON Path and escaped properties, This sample loads JSON with properties that need to be escaped when queried with M:Newtonsoft.Json.Linq.JToken.SelectToken(System.String). Determines whether the JArray contains a specific value. CopyTo: Copies the SelectTokens(String) Selects a collection of elements using a JPath expression.

JSON Path regex operator, This sample loads JSON and then queries values from it using SelectToken( String) with a regex JSON Path. Sample. Usage. Copy. JArray packages = JArray . Overload:Newtonsoft.Json.Linq.JToken.SelectToken provides a method to query LINQ to JSON using a single string path to a desired T:Newtonsoft.Json.Linq.JToken. SelectToken makes dynamic queries easy because the entire query is defined in a string.

Json.NET - Finding an element in a JArray Object, It was an array of items which has got two keys named Name and Country and I on this topic and finally resolved it using the SelectToken method available in JSON. Next up is to parse the json string to an array using the JArray. Now we will make use of the JSONPath queries to search for the item This sample loads JSON and then queries values from it using a combination of M:Newtonsoft.Json.Linq.JToken.SelectToken(System.String) and LINQ operators.

Comments
  • I think, I have ran into the same issue. JsonPath doesn't support expressions to the top level array (please correct me if I'm wrong). You need to add an extra root node and make your array its content.
  • Do you need to put quotes around the id values?
  • @alans sorry that was a typo on my part. There are quotes around it. This is more for testing purposes. The JSON structure parses fine, I am just having trouble querying it. Will update the quesiton
  • @alans actually looking at the response there are no quotes around this value.. would that matter? id is not even used in the query, just path
  • @Tree55Topz Well, without the quotes, my parser is throwing out error with the data.
  • Yeah I think the simpler approach is best here.. No need to use regex. Will go with something like this. Thanks!
  • just bear in mind, that for really large arrays JPath should be much faster