#1 Working with JSON Data
Working with JSON Data
JSON data can be tricky. The easiest way is to convert it to a dynamic object using AsDynamic(string)
. Then you can easily use it in your code.
-
-
⬇️ Result | Source ➡️
- Title:
This is a JSON title
- IsCool:
True
- Sub-item title:
sub-item title
- Is this a list/array?
False
- Are the tags a list?
True
@inherits Custom.Hybrid.RazorTyped
@using System.Collections;
@{
var someJson = System.IO.File.ReadAllText(App.Folder.PhysicalPath + "/tutorials/json-use/demo.json");
var thing = Kit.Json.ToTyped(someJson);
}
<ul>
<li>Title:
@thing.String("Title")
</li>
<li>IsCool:
@thing.Bool("IsCool")
</li>
<li>Sub-item title:
@thing.String("SubItem.Title")
</li>
<li>Is this a list/array?
@(thing is IEnumerable)
</li>
<li>Are the tags a list?
@(thing.Get("Tags") is IEnumerable)
</li>
</ul>
Source Code of demo.json
{
"title": "This is a JSON title",
"isCool": true,
"subItem": {
"title": "sub-item title"
},
"tags": [
"some tag",
"another tag",
"a third tag"
]
}
-
-
⬇️ Result | Source ➡️
System.Collections.Generic.List`1[System.Object]
- some tag
- another tag
- a third tag
@inherits Custom.Hybrid.RazorTyped
@{
var someJson = System.IO.File.ReadAllText(App.Folder.PhysicalPath + "/tutorials/json-use/demo.json");
var thing = Kit.Json.ToTyped(someJson);
}
@thing.Get("Tags")
<ol>
@foreach (var tag in thing.Get("Tags") as IEnumerable<object>) {
<li>@tag</li>
}
</ol>
Source Code of demo.json
{
"title": "This is a JSON title",
"isCool": true,
"subItem": {
"title": "sub-item title"
},
"tags": [
"some tag",
"another tag",
"a third tag"
]
}
-
-
⬇️ Result | Source ➡️
-
title (System.String)
= This is a JSON title
-
isCool (System.Boolean)
= True
-
subItem (ToSic.Sxc.Data.Internal.Typed.WrapObjectTyped)
= {
"title": "sub-item title"
}
-
tags (System.Collections.Generic.List`1[System.Object])
= System.Collections.Generic.List`1[System.Object]
@inherits Custom.Hybrid.RazorTyped
@using System.Collections;
@{
var someJson = System.IO.File.ReadAllText(App.Folder.PhysicalPath + "/tutorials/json-use/demo.json");
var thing = Kit.Json.ToTyped(someJson);
}
<ol>
@foreach (var prop in thing.Keys()) {
<li>
<strong>@prop</strong> (@thing.Get(prop).GetType()) <br>
= @thing.Get(prop)
</li>
}
</ol>
Source Code of demo.json
{
"title": "This is a JSON title",
"isCool": true,
"subItem": {
"title": "sub-item title"
},
"tags": [
"some tag",
"another tag",
"a third tag"
]
}
#1 Working with JSON Data