C
C#2y ago
malkav

❔ Newtonsoft, count nested properties

Some time ago I had a nice chat in here where we found a solution to a problem. Namely counting all properties in a given JSON data structure. Now I want to extend on this, and count only the properties that have an empty value, (or the other way around, only the properties that NOT have an empty value) but I'm not sure how to alter the function we created in an earlier topic to accomodate for this. This was the original "Count all properties" method:
public static Dictionary<string, int> CountNested(this JObject obj, Dictionary<string, int>? countedProperties = null)
{
Dictionary<string, int> countedProps = countedProperties ?? new();
foreach (KeyValuePair<string, JToken> kvp in obj)
{
countedProps.IncrementCount(kvp.Key);
foreach (JObject childJObject in kvp.Value.Children().OfType<JObject>())
{
Dictionary<string, int> childResults = CountNested(childJObject);
foreach (KeyValuePair<string, int> resultKvp in childResults)
{
countedProps.IncrementCount(resultKvp.Key, resultKvp.Value);
}
}
}
return countedProps;
}

private static void IncrementCount(this IDictionary<string, int> dict, string key, int amount = 1)
{
if (dict.ContainsKey(key))
dict[key] += amount;
else
dict[key] = amount;
}
public static Dictionary<string, int> CountNested(this JObject obj, Dictionary<string, int>? countedProperties = null)
{
Dictionary<string, int> countedProps = countedProperties ?? new();
foreach (KeyValuePair<string, JToken> kvp in obj)
{
countedProps.IncrementCount(kvp.Key);
foreach (JObject childJObject in kvp.Value.Children().OfType<JObject>())
{
Dictionary<string, int> childResults = CountNested(childJObject);
foreach (KeyValuePair<string, int> resultKvp in childResults)
{
countedProps.IncrementCount(resultKvp.Key, resultKvp.Value);
}
}
}
return countedProps;
}

private static void IncrementCount(this IDictionary<string, int> dict, string key, int amount = 1)
{
if (dict.ContainsKey(key))
dict[key] += amount;
else
dict[key] = amount;
}
How would I alter this method so it counts only the props that are either empty or not empty (can be two methods if need be)
1 Reply
Accord
Accord2y ago
Looks like nothing has happened here. I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server