I actually had the same problem earlier today, I could not find this question on SO at first, and as a result I wrote my own extension method to return JValue objects containing leaf node values โโof the JSON blob. This is similar to the accepted answer, with the exception of some improvements:
- It processes any JSON that you give it (arrays, properties, etc.), and not just a JSON object.
- Less memory usage
- No
.Count() calls for descendants that you ultimately don't need
Depending on your use case, they may or may not be relevant, but they are for my case. I wrote about learning to align JSON.NET objects on my blog . Here is the extension method I wrote:
public static class JExtensions { public static IEnumerable<JValue> GetLeafValues(this JToken jToken) { if (jToken is JValue jValue) { yield return jValue; } else if (jToken is JArray jArray) { foreach (var result in GetLeafValuesFromJArray(jArray)) { yield return result; } } else if (jToken is JProperty jProperty) { foreach (var result in GetLeafValuesFromJProperty(jProperty)) { yield return result; } } else if (jToken is JObject jObject) { foreach (var result in GetLeafValuesFromJObject(jObject)) { yield return result; } } } #region Private helpers static IEnumerable<JValue> GetLeafValuesFromJArray(JArray jArray) { for (var i = 0; i < jArray.Count; i++) { foreach (var result in GetLeafValues(jArray[i])) { yield return result; } } } static IEnumerable<JValue> GetLeafValuesFromJProperty(JProperty jProperty) { foreach (var result in GetLeafValues(jProperty.Value)) { yield return result; } } static IEnumerable<JValue> GetLeafValuesFromJObject(JObject jObject) { foreach (var jToken in jObject.Children()) { foreach (var result in GetLeafValues(jToken)) { yield return result; } } } #endregion }
Then in my calling code, I simply extract the Path and Value properties from the JValue of JValue objects:
var jToken = JToken.Parse("blah blah json here"); foreach (var jValue in jToken.GetLeafValues()) { Console.WriteLine("{0} = {1}", jValue.Path, jValue.Value); }
watkinsmatthewp
source share