Karl Gardner
Karl Gardner

Reputation: 63

JSON Path Expression Filter Property Filtering on property values in a Single Object

I am using Newtonsoft.Json and the SelectTokens method of the JObject. I am trying to get only the properties that do not have an empty array as it's value. Here is the current code that I am trying and it doesn't seem to working :(

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

var item = JObject.Parse(@"
  {
    'date': '2024-12-27',
    'availability': {
      '7:00': [],
      '8:00': [],
      '9:00': [],
      '10:00': [
        {
          'id': 2583
        }
      ]
    }
  }
  ");


var availability = item.SelectTokens("$.availability.*[?(length()>0)]").ToList();

Anyone have an idea to only get the property names (using the filter expression) of the availability object that have an array length greater than 0? This currently gives me an exception.

Thanks!

Upvotes: 0

Views: 51

Answers (1)

AVTUNEY
AVTUNEY

Reputation: 1270

You don't need to use SelectTokens(), simply use Properties() after you cast an object as JObject

var availabilityObject = item["availability"] as JObject;
var nonEmptyKeys = availabilityObject.Properties()
    .Where(p => p.Value is JArray array && array.Count > 0)
    .Select(p => p.Name)
    .ToList();

Fiddle link CLICK ME

Upvotes: 0

Related Questions