Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- var jsons = new[]
- {
- @"{""foo"":""fooo"", ""qux"":{ ""bar"":1, ""baz"":0.5}}",
- @"{""foo"":""fooo"", ""qux"":{ ""bar"":2, ""baz"":1.5}}",
- @"{""foo"":""fooo"", ""qux"":{ ""bar"":2, ""baaz"":""2012-04-23T18:25:43.511Z""}}",
- };
- var flat =
- jsons
- .Select(JObjectVisitor.Flatten)
- .ToDataTable();
- flat.Compute("sum([qux.baz])", null).Dump(); // 2
- flat.Compute("sum([qux.baz]) < 3", null).Dump(); // True
- public class JObjectVisitor
- {
- private readonly IDictionary<string, object> _flat;
- private JObjectVisitor(JObject source)
- {
- _flat = new Dictionary<string, object>();
- VisitJObject(source);
- }
- public static IDictionary<string, object> Flatten(string json)
- {
- var obj = JObject.Parse(json);
- return new JObjectVisitor(obj)._flat;
- }
- public static IDictionary<string, object> Flatten(JObject source)
- {
- return new JObjectVisitor(source)._flat;
- }
- private void VisitJObject(JObject source)
- {
- foreach (var item in source)
- {
- switch (item.Value)
- {
- case JObject jObject:
- VisitJObject(jObject);
- break;
- case JValue jValue:
- VisitJValue(jValue);
- break;
- case JArray jArray:
- VisitJArray(jArray);
- break;
- }
- }
- }
- private void VisitJArray(JArray jArray)
- {
- // not used
- }
- private void VisitJValue(JValue jValue)
- {
- _flat[jValue.Path] = jValue.Value;
- }
- }
- public static DataTable ToDataTable(this IEnumerable<IDictionary<string, object>> source)
- {
- return
- source
- .Aggregate(new DataTable(), (current, next) =>
- {
- var newRow = current.NewRow();
- foreach (var item in next.Where(x => !(x.Value is null)))
- {
- if (!current.Columns.Contains(item.Key))
- {
- current.Columns.Add(new DataColumn(item.Key, item.Value.GetType()));
- }
- newRow[item.Key] = item.Value;
- }
- current.Rows.Add(newRow);
- return current;
- });
- }
Add Comment
Please, Sign In to add comment