-
-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathJsonFlattener.cs
515 lines (493 loc) · 19.4 KB
/
JsonFlattener.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
using System;
using System.Diagnostics;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Text.Json;
namespace JsonCons.Utilities
{
/// <summary>
/// Defines how the unflatten operation handles integer tokens in a JSON Pointer
/// </summary>
/// <example>
/// This example illustrates the use of <see cref="IntegerTokenUnflattening"/>
/// <code>
/// using System;
/// using System.Diagnostics;
/// using System.Text.Json;
/// using JsonCons.Utilities;
///
/// public class Example
/// {
/// public static void Main()
/// {
/// using var doc = JsonDocument.Parse(@"
/// {
/// ""discards"": {
/// ""1000"": ""Record does not exist"",
/// ""1004"": ""Queue limit exceeded"",
/// ""1010"": ""Discarding timed-out partial msg""
/// },
/// ""warnings"": {
/// ""0"": ""Phone number missing country code"",
/// ""1"": ""State code missing"",
/// ""2"": ""Zip code missing""
/// }
/// }
/// ");
///
/// var options = new JsonSerializerOptions() { WriteIndented = true };
///
/// using JsonDocument flattened = JsonFlattener.Flatten(doc.RootElement);
/// Console.WriteLine("The flattened document:\n");
/// Console.WriteLine($"{JsonSerializer.Serialize(flattened, options)}\n");
///
/// Console.WriteLine("Unflatten integer tokens as array indices if possible:\n");
/// using JsonDocument unflattened1 = JsonFlattener.Unflatten(flattened.RootElement,
/// IntegerTokenUnflattening.TryIndex);
/// Console.WriteLine($"{JsonSerializer.Serialize(unflattened1, options)}\n");
///
/// Console.WriteLine("Always unflatten integer tokens as object names:\n");
/// using JsonDocument unflattened2 = JsonFlattener.Unflatten(flattened.RootElement,
/// IntegerTokenUnflattening.AssumeName);
/// Console.WriteLine($"{JsonSerializer.Serialize(unflattened2, options)}\n");
/// }
/// }
/// </code>
/// Output:
/// <code>
/// The flattened document:
///
/// {
/// "/discards/1000": "Record does not exist",
/// "/discards/1004": "Queue limit exceeded",
/// "/discards/1010": "Discarding timed-out partial msg",
/// "/warnings/0": "Phone number missing country code",
/// "/warnings/1": "State code missing",
/// "/warnings/2": "Zip code missing"
/// }
///
/// Unflatten integer tokens as array indices if possible:
///
/// {
/// "discards": {
/// "1000": "Record does not exist",
/// "1004": "Queue limit exceeded",
/// "1010": "Discarding timed-out partial msg"
/// },
/// "warnings": [
/// "Phone number missing country code",
/// "State code missing",
/// "Zip code missing"
/// ]
/// }
///
/// Always unflatten integer tokens as object names:
///
/// {
/// "discards": {
/// "1000": "Record does not exist",
/// "1004": "Queue limit exceeded",
/// "1010": "Discarding timed-out partial msg"
/// },
/// "warnings": {
/// "0": "Phone number missing country code",
/// "1": "State code missing",
/// "2": "Zip code missing"
/// }
/// }
/// </code>
/// </example>
public enum IntegerTokenUnflattening {
/// <summary>
/// The unflatten operation first tries to unflatten into a JSON array
/// using the integer tokens as sequential indices, and if that fails, unflattens into
/// a JSON object using the integer tokens as names.
/// </summary>
TryIndex,
/// <summary>
/// The unflatten operation always unflattens into a JSON object
/// using the integer tokens as names.
/// </summary>
AssumeName
}
/// <summary>
/// Provides functionality to flatten a JSON object or array to a single depth JSON object of JSON Pointer-value pairs,
/// and to unflatten a flattened JSON object.
/// </summary>
/// <example>
/// This example shows how to flatten and unflatten a JSON value
/// <code>
/// using System;
/// using System.Diagnostics;
/// using System.Text.Json;
/// using JsonCons.Utilities;
///
/// public class Example
/// {
/// public static void Main()
/// {
/// using var doc = JsonDocument.Parse(@"
/// {
/// ""application"": ""hiking"",
/// ""reputons"": [
/// {
/// ""rater"": ""HikingAsylum"",
/// ""assertion"": ""advanced"",
/// ""rated"": ""Marilyn C"",
/// ""rating"": 0.90
/// },
/// {
/// ""rater"": ""HikingAsylum"",
/// ""assertion"": ""intermediate"",
/// ""rated"": ""Hongmin"",
/// ""rating"": 0.75
/// }
/// ]
/// }
/// ");
///
/// using JsonDocument flattened = JsonFlattener.Flatten(doc.RootElement);
///
/// var options = new JsonSerializerOptions() { WriteIndented = true };
///
/// Console.WriteLine($"{JsonSerializer.Serialize(flattened, options)}\n");
///
/// using JsonDocument unflattened = JsonFlattener.Unflatten(flattened.RootElement);
///
/// var comparer = JsonElementEqualityComparer.Instance;
/// Debug.Assert(comparer.Equals(unflattened.RootElement,doc.RootElement));
/// }
/// }
/// </code>
/// Output:
/// <code>
/// {
/// "/application": "hiking",
/// "/reputons/0/rater": "HikingAsylum",
/// "/reputons/0/assertion": "advanced",
/// "/reputons/0/rated": "Marilyn C",
/// "/reputons/0/rating": 0.90,
/// "/reputons/1/rater": "HikingAsylum",
/// "/reputons/1/assertion": "intermediate",
/// "/reputons/1/rated": "Hongmin",
/// "/reputons/1/rating": 0.75
/// }
/// </code>
/// </example>
public static class JsonFlattener
{
/// <summary>
/// Converts a JSON object or array into a single depth JSON object of name-value pairs,
/// such that the names are JSON Pointer strings, and the values are either string,
/// number, true, false, null, empty object, or empty array.
/// </summary>
/// <remarks>
/// It is the users responsibilty to properly Dispose the returned <see cref="JsonDocument"/> value
/// </remarks>
/// <param name="value">The value to be flattened.</param>
/// <returns>The flattened value</returns>
public static JsonDocument Flatten(JsonElement value)
{
var result = new JsonDocumentBuilder(JsonValueKind.Object);
string parentKey = "";
_Flatten(parentKey, value, result);
return result.ToJsonDocument();
}
/// <summary>
/// Recovers the orginal JSON value from a JSON object in flattened form, to the extent possible.
/// There may not be a unique solution, an integer token in a JSON Pointer could be an array index or
/// it could be an object name. The default behavior is to attempt to recover arrays. The <paramref name="options"/>
/// parameter can be used to recover objects with integer names instead.
/// </summary>
/// <remarks>
/// It is the users responsibilty to properly Dispose the returned <see cref="JsonDocument"/> value
/// </remarks>
/// <param name="flattenedValue">The flattened value, which must be a JSON object of name-value pairs, such that
/// the names are JSON Pointer strings, and the values are either string,
/// number, true, false, null, empty object, or empty array.</param>
/// <param name="options">Options for handling integer tokens in the JSON Pointer.</param>
/// <returns>The unflattened value</returns>
/// <exception cref="ArgumentException">
/// The <paramref name="flattenedValue"/> is not a JSON object, or has a name that contains an invalid JSON pointer.
/// </exception>
public static JsonDocument Unflatten(JsonElement flattenedValue,
IntegerTokenUnflattening options = IntegerTokenUnflattening.TryIndex)
{
if (options == IntegerTokenUnflattening.TryIndex)
{
JsonDocumentBuilder val;
if (TryUnflattenArray(flattenedValue, out val))
{
return val.ToJsonDocument();
}
else
{
return UnflattenToObject(flattenedValue, options).ToJsonDocument();
}
}
else
{
return UnflattenToObject(flattenedValue, options).ToJsonDocument();
}
}
static void _Flatten(string parentKey,
JsonElement parentValue,
JsonDocumentBuilder result)
{
switch (parentValue.ValueKind)
{
case JsonValueKind.Array:
{
if (parentValue.GetArrayLength() == 0)
{
result.AddProperty(parentKey, new JsonDocumentBuilder(parentValue));
}
else
{
for (int i = 0; i < parentValue.GetArrayLength(); ++i)
{
var buffer = new StringBuilder(parentKey);
buffer.Append('/');
buffer.Append(i.ToString());
_Flatten(buffer.ToString(), parentValue[i], result);
}
}
break;
}
case JsonValueKind.Object:
{
if (parentValue.EnumerateObject().Count() == 0)
{
result.AddProperty(parentKey, new JsonDocumentBuilder(parentValue));
}
else
{
foreach (var item in parentValue.EnumerateObject())
{
var buffer = new StringBuilder(parentKey);
buffer.Append('/');
buffer.Append(JsonPointer.Escape(item.Name));
_Flatten(buffer.ToString(), item.Value, result);
}
}
break;
}
default:
{
result.AddProperty(parentKey, new JsonDocumentBuilder(parentValue));
break;
}
}
}
// unflatten
static JsonDocumentBuilder SafeUnflatten(JsonDocumentBuilder value)
{
if (value.ValueKind != JsonValueKind.Object || value.GetObjectLength() == 0)
{
return value;
}
bool safe = true;
int index = 0;
foreach (var item in value.EnumerateObject())
{
int n;
if (!int.TryParse(item.Key, out n) || index++ != n)
{
safe = false;
break;
}
}
if (safe)
{
var j = new JsonDocumentBuilder(JsonValueKind.Array);
foreach (var item in value.EnumerateObject())
{
j.AddArrayItem(item.Value);
}
var a = new JsonDocumentBuilder(JsonValueKind.Array);
foreach (var item in j.EnumerateArray())
{
a.AddArrayItem(SafeUnflatten(item));
}
return a;
}
else
{
var o = new JsonDocumentBuilder(JsonValueKind.Object);
foreach (var item in value.EnumerateObject())
{
//if (!o.ContainsPropertyName(item.Key))
//{
// o.AddProperty(item.Key, SafeUnflatten (item.Value));
//}
o.TryAddProperty(item.Key, SafeUnflatten (item.Value));
}
return o;
}
}
static bool TryUnflattenArray(JsonElement value, out JsonDocumentBuilder result)
{
if (value.ValueKind != JsonValueKind.Object)
{
throw new ArgumentException("The value to unflatten is not a JSON object");
}
result = new JsonDocumentBuilder(JsonValueKind.Object);
foreach (var item in value.EnumerateObject())
{
JsonDocumentBuilder? parent = null;
JsonDocumentBuilder part = result;
int parentIndex = 0;
string parentName = "";
JsonPointer ptr;
if (!JsonPointer.TryParse(item.Name, out ptr))
{
throw new ArgumentException("Name contains invalid JSON Pointer");
}
int index = 0;
var it = ptr.GetEnumerator();
bool more = it.MoveNext();
while (more)
{
string token = it.Current;
int n;
if (int.TryParse(token, out n) && index++ == n)
{
if (part.ValueKind != JsonValueKind.Array)
{
if (parent != null && parent.ValueKind == JsonValueKind.Object)
{
parent.RemoveProperty(parentName);
var val = new JsonDocumentBuilder(JsonValueKind.Array);
parent.AddProperty(parentName, val);
part = val;
}
else if (parent != null && parent.ValueKind == JsonValueKind.Array)
{
var val = new JsonDocumentBuilder(JsonValueKind.Array);
parent[parentIndex] = val;
part = val;
}
else
{
return false;
}
}
parent = part;
parentIndex = n;
parentName = token;
more = it.MoveNext();
if (more)
{
if (n >= part.GetArrayLength())
{
part.AddArrayItem(new JsonDocumentBuilder(JsonValueKind.Object));
part = part[part.GetArrayLength() - 1];
}
else
{
part = part[n];
}
}
else
{
part.AddArrayItem(new JsonDocumentBuilder(item.Value));
part = part[part.GetArrayLength() - 1];
}
}
else if (part.ValueKind == JsonValueKind.Object)
{
more = it.MoveNext();
if (more)
{
JsonDocumentBuilder val;
if (part.TryGetProperty(token, out val))
{
part = val;
}
else
{
val = new JsonDocumentBuilder(JsonValueKind.Object);
part.AddProperty(token,val);
part = val;
}
}
else
{
JsonDocumentBuilder val;
if (part.TryGetProperty(token, out val))
{
part = val;
}
else
{
val = new JsonDocumentBuilder(item.Value);
part.AddProperty(token,val);
part = val;
}
}
}
else
{
return false;
}
}
}
return true;
}
static JsonDocumentBuilder UnflattenToObject(JsonElement value, IntegerTokenUnflattening options = IntegerTokenUnflattening.TryIndex)
{
if (value.ValueKind != JsonValueKind.Object)
{
throw new ArgumentException("The value to unflatten is not a JSON object");
}
var result = new JsonDocumentBuilder(JsonValueKind.Object);
foreach (var item in value.EnumerateObject())
{
JsonDocumentBuilder part = result;
JsonPointer ptr;
if (!JsonPointer.TryParse(item.Name, out ptr))
{
throw new ArgumentException("Name contains invalid JSON Pointer");
}
var it = ptr.GetEnumerator();
bool more = it.MoveNext();
while (more)
{
var s = it.Current;
more = it.MoveNext();
if (more)
{
JsonDocumentBuilder val;
if (part.TryGetProperty(s, out val))
{
part = val;
}
else
{
val = new JsonDocumentBuilder(JsonValueKind.Object);
part.AddProperty(s,val);
part = val;
}
}
else
{
JsonDocumentBuilder val;
if (part.TryGetProperty(s, out val))
{
part = val;
}
else
{
val = new JsonDocumentBuilder(item.Value);
part.AddProperty(s,val);
part = val;
}
}
}
}
return options == IntegerTokenUnflattening.TryIndex ? SafeUnflatten (result) : result;
}
}
} // namespace JsonCons.Utilities