Skip to main content
Home  › ... Razor

JSON Tutorials

Tutorial HomeJSON
The samples can differ based on your Razor base class or if you're running an old version.
Switch to Typed (2sxc 16+) Switch to Dynamic (Razor14 or below)
Requirements

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]
  1. some tag
  2. another tag
  3. 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 ➡️

  1. title (System.String)
    = This is a JSON title
  2. isCool (System.Boolean)
    = True
  3. subItem (ToSic.Sxc.Data.Internal.Typed.WrapObjectTyped)
    = { "title": "sub-item title" }
  4. 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"
    ]
}