Search code examples
json.netjsonpathjson-path-expression

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+/)]


Solution

  • 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 [].)