-
Notifications
You must be signed in to change notification settings - Fork 369
/
JsonExtensions.cs
80 lines (64 loc) · 2.62 KB
/
JsonExtensions.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
// Copyright(c).NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Text.Json;
using Microsoft.DotNet.Interactive.Formatting.TabularData;
namespace Microsoft.DotNet.Interactive.Formatting;
public static class JsonExtensions
{
public static TabularDataResource ToTabularDataResource(this JsonDocument document)
{
return document.RootElement.ToTabularDataResource();
}
public static TabularDataResource ToTabularDataResource(this JsonElement jsonElement)
{
if (jsonElement.ValueKind != JsonValueKind.Array)
{
throw new InvalidOperationException("input must be a valid array of object");
}
var rows = new List<IEnumerable<KeyValuePair<string, object>>>();
foreach (var element in jsonElement.EnumerateArray())
{
if (element.ValueKind == JsonValueKind.Object)
{
var row = new List<KeyValuePair<string, object>>();
foreach (var property in element.EnumerateObject())
{
row.Add(new KeyValuePair<string, object>(
property.Name,
property.Value.ValueKind switch
{
JsonValueKind.String => property.Value.GetString(),
JsonValueKind.Number => GetNumber(property.Value),
JsonValueKind.True => true,
JsonValueKind.False => false,
JsonValueKind.Null => null,
JsonValueKind.Undefined => property.Value,
JsonValueKind.Object => property.Value,
JsonValueKind.Array => property.Value,
_ => throw new ArgumentOutOfRangeException()
}));
}
rows.Add(row);
}
}
return rows.ToTabularDataResource();
static object GetNumber(JsonElement propertyValue)
{
if (propertyValue.TryGetInt32(out var integer))
{
return integer;
}
if (propertyValue.TryGetInt64(out var longInt))
{
return longInt;
}
if (propertyValue.TryGetDouble(out var doublePrecision))
{
return doublePrecision;
}
return propertyValue.GetDecimal();
}
}
}