Guest User

Untitled

a guest
Feb 20th, 2018
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.26 KB | None | 0 0
  1. var jsons = new[]
  2. {
  3. @"{""foo"":""fooo"", ""qux"":{ ""bar"":1, ""baz"":0.5}}",
  4. @"{""foo"":""fooo"", ""qux"":{ ""bar"":2, ""baz"":1.5}}",
  5. @"{""foo"":""fooo"", ""qux"":{ ""bar"":2, ""baaz"":""2012-04-23T18:25:43.511Z""}}",
  6. };
  7.  
  8. var flat =
  9. jsons
  10. .Select(JObjectVisitor.Flatten)
  11. .ToDataTable();
  12.  
  13. flat.Compute("sum([qux.baz])", null).Dump(); // 2
  14. flat.Compute("sum([qux.baz]) < 3", null).Dump(); // True
  15.  
  16. public class JObjectVisitor
  17. {
  18. private readonly IDictionary<string, object> _flat;
  19.  
  20. private JObjectVisitor(JObject source)
  21. {
  22. _flat = new Dictionary<string, object>();
  23.  
  24. VisitJObject(source);
  25. }
  26.  
  27. public static IDictionary<string, object> Flatten(string json)
  28. {
  29. var obj = JObject.Parse(json);
  30. return new JObjectVisitor(obj)._flat;
  31. }
  32.  
  33. public static IDictionary<string, object> Flatten(JObject source)
  34. {
  35. return new JObjectVisitor(source)._flat;
  36. }
  37.  
  38. private void VisitJObject(JObject source)
  39. {
  40. foreach (var item in source)
  41. {
  42. switch (item.Value)
  43. {
  44. case JObject jObject:
  45. VisitJObject(jObject);
  46. break;
  47. case JValue jValue:
  48. VisitJValue(jValue);
  49. break;
  50. case JArray jArray:
  51. VisitJArray(jArray);
  52. break;
  53. }
  54. }
  55. }
  56.  
  57. private void VisitJArray(JArray jArray)
  58. {
  59. // not used
  60. }
  61.  
  62. private void VisitJValue(JValue jValue)
  63. {
  64. _flat[jValue.Path] = jValue.Value;
  65. }
  66. }
  67.  
  68. public static DataTable ToDataTable(this IEnumerable<IDictionary<string, object>> source)
  69. {
  70. return
  71. source
  72. .Aggregate(new DataTable(), (current, next) =>
  73. {
  74. var newRow = current.NewRow();
  75.  
  76. foreach (var item in next.Where(x => !(x.Value is null)))
  77. {
  78. if (!current.Columns.Contains(item.Key))
  79. {
  80. current.Columns.Add(new DataColumn(item.Key, item.Value.GetType()));
  81. }
  82. newRow[item.Key] = item.Value;
  83. }
  84. current.Rows.Add(newRow);
  85.  
  86. return current;
  87. });
  88. }
Add Comment
Please, Sign In to add comment