1

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.

Dan Atkinson
  • 11,391
  • 14
  • 81
  • 114
Trinitron
  • 374
  • 3
  • 12

1 Answers1

2

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);
Guru Stron
  • 102,774
  • 10
  • 95
  • 132