Search code examples
c#json.netjpath

What is jpath for {"Type":"Ping"} in Json.Net?


I have a simple string from webSockets. And i stuck on jPath for SelectTokens() method. Is there any path which can help me grab $.Type only if it is equal to 'Ping'?

var str= @"{""Type"":""Ping""}";
var token = JObject.Parse(str).SelectToken("$.Type =='Ping'");

This is c# app and standard Json.Net lib is used.


Solution

  • You can just check the token value after select:

    var token = JObject.Parse(str).SelectToken("$.Type");
    Console.WriteLine(token?.Value<string>() == "Ping");
    

    If you have an array in your json you can use json path filters:

    var str= @"{""root"": [{""Type"":""Ping""}]}";
    var token = JObject.Parse(str).SelectTokens("$.root[?(@.Type == 'Ping')]");
    

    Next will select the whole property:

    var token = JObject.Parse(str).SelectToken("$[?($.Type == 'Ping')]");
    Console.WriteLine(token);