Prasad Korhale
Prasad Korhale

Reputation: 619

JSON path expression for regex matching property names

{ 
   "PORT" : {
      "Ethernet0": {
         "id": 0 
      },
      "Ethernet1": {
         "id" : 1
      },
      "Foo": {
         "id": 2
      }
   }
}

Given the above JSON, how can I fetch all the objects under PORT that matches the Ethernet* pattern? Most of the examples that I saw online or in the test cases for JSON.Net showcase an example of doing so based on an array.

I am using the JToken.SelectTokens API from the c# Newtonsoft.Json package. I think the query should look something like below. But it does not work. Any help is highly appreciated!

$.PORT.[?(@ =~ /Ethernet\d+/)]

Upvotes: 0

Views: 87

Answers (2)

gregsdennis
gregsdennis

Reputation: 8428

JSON Path doesn't have a way to apply a regex to the key, only the value.

Specifically for Newtonsoft: https://www.newtonsoft.com/json/help/html/RegexQuery.htm

For RFC9535, which is relatively new, so many implementations haven't yet updated: https://www.rfc-editor.org/rfc/rfc9535.html#name-search-function-extension

We do also have a few issues that may be interest:

(A selector is the bit that goes in the [].)

Upvotes: 2

n___dv
n___dv

Reputation: 314

you can do it like this $.PORT.* will get all the child of port.

 string json = @"{ 
                           'PORT': {
                               'Ethernet0': { 'id': 0 },
                               'Ethernet1': { 'id': 1 }
                           }
                        }";

        JObject jObject = JObject.Parse(json);

        // Use SelectTokens to get all Ethernet objects
        IEnumerable<JToken> ethernetObjects = jObject.SelectTokens("$.PORT.*");
         
         foreach (JToken ethernet in ethernetObjects)
        {
            Console.WriteLine(ethernet);
        }

Upvotes: 0

Related Questions