Reputation: 435
i have a large json data and i want to get all paths from the root until getting value for the paths then storing the result to a string as i described bellow here is my json for example
{
"root":{
"first":{
"first1":{
"value":"1"
},
"first2":{
"value":"2"
},
"first3":{
"value":"3"
}
},
"second":{
"second1":{
"value":"1"
},
"second2":{
"value":"2"
},
"second3":{
"value":"3"
}
},
"third":{
"third1":{
"value":"1"
},
"third2":{
"value":"2"
},
"third3":{
"value":"3"
}
},
"four":{
"value":"4"
},
"five":{
"five1":{
"five11":{
"value":"five11"
},
"five12":{
"value":"five12"
}
},
"five2":{
"five21":{
"five211":{
"value":"five211"
}
}
}
}
}
}
then i want to make each paths like bellow dynamically in c# and showing in screen please tell me a way to make this
root.first.first1.value
root.first.first2.value
root.first.first3.value
root.second.second1.value
......
root.four.value
root.five.five1.five11.value
root.five.five1.five12.value
....
root.five2.five21.five211.value
Upvotes: 2
Views: 1287
Reputation: 335
Use JSON.NET and iterate recursively through the Children property and check if the current token doesn't have HasValues set to true and if that's the case add the Path property of that token to a StringBuilder or what have you. Should give you exactly what you want.
Edith: Code Sample
I was lazy and just included the whole console application code.
using System;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Text;
public class Program
{
public static void Main()
{
var json = @"
{
""root"":{
""first"":{
""first1"":{
""value"":""1""
},
""first2"":{
""value"":""2""
},
""first3"":{
""value"":""3""
}
}
}
}";
var jobject = JObject.Parse (json);
var sb = new StringBuilder ();
RecursiveParse (sb, jobject);
Console.WriteLine (sb.ToString());
}
public static void RecursiveParse(StringBuilder sb, JToken token)
{
foreach (var item in token.Children()) {
if (item.HasValues)
{
RecursiveParse (sb, item);
} else {
sb.AppendLine (item.Path);
}
}
}
}
Upvotes: 6