-
Notifications
You must be signed in to change notification settings - Fork 368
/
JsonExtensions.cs
57 lines (48 loc) · 2.07 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
// 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 dictionaries = new List<Dictionary<string, object>>();
foreach (var element in jsonElement.EnumerateArray())
{
if (element.ValueKind == JsonValueKind.Object)
{
var dict = new Dictionary<string, object>();
foreach (var property in element.EnumerateObject())
{
dict.Add(
property.Name,
property.Value.ValueKind switch
{
JsonValueKind.String => property.Value.GetString(),
JsonValueKind.Number => property.Value.GetSingle(),
JsonValueKind.True => true,
JsonValueKind.False => false,
JsonValueKind.Null => null,
JsonValueKind.Undefined => property.Value,
JsonValueKind.Object => property.Value,
JsonValueKind.Array => property.Value,
_ => throw new ArgumentOutOfRangeException()
});
}
dictionaries.Add(dict);
}
}
return dictionaries.ToTabularDataResource();
}
}