|
| 1 | +using System; |
| 2 | +using System.Collections.Generic; |
| 3 | +using System.Linq; |
| 4 | +using System.Text.RegularExpressions; |
| 5 | +using Newtonsoft.Json.Linq; |
| 6 | + |
| 7 | +namespace DataToolChain |
| 8 | +{ |
| 9 | + |
| 10 | + //https://raw.githubusercontent.com/GFoley83/JsonFlatten/master/JsonFlatten/JsonExtensions.cs |
| 11 | + public static class JsonFlattenExtensions |
| 12 | + { |
| 13 | + /// <summary> |
| 14 | + /// Flattens a JObject to a Dictionary.<c>null</c>, <c>""</c>, <c>[]</c> and <c>{}</c> are preserved by default |
| 15 | + /// </summary> |
| 16 | + /// <param name="jsonObject">JObject to flatten</param> |
| 17 | + /// <param name="includeNullAndEmptyValues">Set to false to ignore JSON properties that are null, "", [] and {} when flattening</param> |
| 18 | + public static IDictionary<string, object> Flatten(this JObject jsonObject, bool includeNullAndEmptyValues = true) => jsonObject |
| 19 | + .Descendants() |
| 20 | + .Where(p => !p.Any()) |
| 21 | + .Aggregate(new Dictionary<string, object>(), (properties, jToken) => |
| 22 | + { |
| 23 | + var value = (jToken as JValue)?.Value; |
| 24 | + |
| 25 | + if (!includeNullAndEmptyValues) |
| 26 | + { |
| 27 | + if (value?.Equals("") == false) |
| 28 | + { |
| 29 | + properties.Add(jToken.Path, value); |
| 30 | + } |
| 31 | + return properties; |
| 32 | + } |
| 33 | + |
| 34 | + var strVal = jToken.Value<object>()?.ToString().Trim(); |
| 35 | + if (strVal?.Equals("[]") == true) |
| 36 | + { |
| 37 | + value = Enumerable.Empty<object>(); |
| 38 | + } |
| 39 | + else if (strVal?.Equals("{}") == true) |
| 40 | + { |
| 41 | + value = new object(); |
| 42 | + } |
| 43 | + |
| 44 | + properties.Add(jToken.Path, value); |
| 45 | + |
| 46 | + return properties; |
| 47 | + }); |
| 48 | + |
| 49 | + /// <summary> |
| 50 | + /// Unflattens an already flattened JSON Dictionary to its original JSON structure |
| 51 | + /// </summary> |
| 52 | + /// <param name="flattenedJsonKeyValues">Dictionary to unflatten</param> |
| 53 | + public static JObject Unflatten(this IDictionary<string, object> flattenedJsonKeyValues) |
| 54 | + { |
| 55 | + JContainer result = null; |
| 56 | + var setting = new JsonMergeSettings |
| 57 | + { |
| 58 | + MergeArrayHandling = MergeArrayHandling.Merge |
| 59 | + }; |
| 60 | + |
| 61 | + foreach (var pathValue in flattenedJsonKeyValues) |
| 62 | + { |
| 63 | + if (result == null) |
| 64 | + { |
| 65 | + result = UnflattenSingle(pathValue); |
| 66 | + } |
| 67 | + else |
| 68 | + { |
| 69 | + result.Merge(UnflattenSingle(pathValue), setting); |
| 70 | + } |
| 71 | + } |
| 72 | + return result as JObject; |
| 73 | + } |
| 74 | + |
| 75 | + /// <summary> |
| 76 | + /// Get an item from the dictionary and cast it to a type. |
| 77 | + /// </summary> |
| 78 | + /// <typeparam name="T"></typeparam> |
| 79 | + /// <param name="dictionary"></param> |
| 80 | + /// <param name="key"></param> |
| 81 | + /// <returns></returns> |
| 82 | + public static T Get<T>(this IDictionary<string, object> dictionary, string key) => (T)dictionary[key]; |
| 83 | + |
| 84 | + /// <summary> |
| 85 | + /// Update an item in the dictionary |
| 86 | + /// </summary> |
| 87 | + /// <param name="dictionary"></param> |
| 88 | + /// <param name="key"></param> |
| 89 | + /// <param name="value"></param> |
| 90 | + public static void Set(this IDictionary<string, object> dictionary, string key, object value) => dictionary[key] = value; |
| 91 | + |
| 92 | + /// <summary> |
| 93 | + /// Try get an item from the dictionary and cast it to a type. |
| 94 | + /// </summary> |
| 95 | + /// <typeparam name="T"></typeparam> |
| 96 | + /// <param name="dictionary"></param> |
| 97 | + /// <param name="key"></param> |
| 98 | + /// <param name="value"></param> |
| 99 | + /// <returns></returns> |
| 100 | + public static bool TryGet<T>(this IDictionary<string, object> dictionary, string key, out T value) |
| 101 | + { |
| 102 | + object result; |
| 103 | + if (dictionary.TryGetValue(key, out result) && result is T) |
| 104 | + { |
| 105 | + value = (T)result; |
| 106 | + return true; |
| 107 | + } |
| 108 | + value = default(T); |
| 109 | + return false; |
| 110 | + } |
| 111 | + |
| 112 | + private static JContainer UnflattenSingle(KeyValuePair<string, object> keyValue) |
| 113 | + { |
| 114 | + var path = keyValue.Key; |
| 115 | + JToken value = keyValue.Value != null ? JToken.FromObject(keyValue.Value) : null; |
| 116 | + var pathSegments = SplitPath(path); |
| 117 | + |
| 118 | + JContainer lastItem = null; |
| 119 | + //build from leaf to root |
| 120 | + foreach (var pathSegment in pathSegments.Reverse()) |
| 121 | + { |
| 122 | + if (!IsJsonArray(pathSegment)) |
| 123 | + { |
| 124 | + var obj = new JObject(); |
| 125 | + if (lastItem == null) |
| 126 | + { |
| 127 | + obj.Add(pathSegment, value); |
| 128 | + } |
| 129 | + else |
| 130 | + { |
| 131 | + obj.Add(pathSegment, lastItem); |
| 132 | + } |
| 133 | + lastItem = obj; |
| 134 | + |
| 135 | + continue; |
| 136 | + } |
| 137 | + |
| 138 | + var array = new JArray(); |
| 139 | + var index = GetArrayIndex(pathSegment); |
| 140 | + array = FillEmpty(array, index); |
| 141 | + array[index] = lastItem ?? value; |
| 142 | + lastItem = array; |
| 143 | + |
| 144 | + } |
| 145 | + return lastItem; |
| 146 | + } |
| 147 | + |
| 148 | + private static IList<string> SplitPath(string path) |
| 149 | + { |
| 150 | + var result = new List<string>(); |
| 151 | + var reg = new Regex(@"(?!\.)([^. ^\[\]]+)|(?!\[)(\d+)(?=\])"); |
| 152 | + foreach (Match match in reg.Matches(path)) |
| 153 | + { |
| 154 | + result.Add(match.Value); |
| 155 | + } |
| 156 | + return result; |
| 157 | + } |
| 158 | + |
| 159 | + private static JArray FillEmpty(JArray array, int index) |
| 160 | + { |
| 161 | + for (var i = 0; i <= index; i++) |
| 162 | + { |
| 163 | + array.Add(null); |
| 164 | + } |
| 165 | + return array; |
| 166 | + } |
| 167 | + |
| 168 | + private static bool IsJsonArray(string pathSegment) => int.TryParse(pathSegment, out var x); |
| 169 | + |
| 170 | + private static int GetArrayIndex(string pathSegment) |
| 171 | + { |
| 172 | + if (int.TryParse(pathSegment, out var result)) |
| 173 | + { |
| 174 | + return result; |
| 175 | + } |
| 176 | + throw new Exception($"Unable to parse array index: {pathSegment}"); |
| 177 | + } |
| 178 | + } |
| 179 | +} |
0 commit comments