Guru
Guru

Reputation: 47

Blazor - Split data from JSON and display in HTML

Using the below code to parse value from JSON and display it in HTML in one of my Blazor project.

But struggling to split value of 'Ring_Position' from JSON and display it into two parts in HTML.

For Eg: 19.274:2102 should be displayed as 19.274 mm - 2102 °C

Below is the code used for JSON to HTML mapping

private UnloadDetails[]? unloads;

protected override async Task OnInitializedAsync()
{
    unloads = await Http.GetFromJsonAsync<UnloadDetails[]>("sample-data/unload.json");

}

public class UnloadDetails
{
    public String? Operator { get; set; }
    public string? Tool_ID { get; set; }
    public string? Notes { get; set; }
    public Dictionary<string, object> Ring_Position { get; set; }     
}

JSON:

"Ring_Position": {
      "1-01": "19.274:1202",
      "1-02": "19.271:1202",
      "1-03": "19.297:1200",
      "1-04": "19.307:1198"
}
<div class="ring-Details" style="font-weight: lighter; font-size: small;">@labels.Ring_Position["1-03"]</div>

Upvotes: 1

Views: 1240

Answers (1)

Yong Shun
Yong Shun

Reputation: 51295

Working with Regular Expression

^(\d+.\d+):(\d+)$

From provided input, capture the first group with pattern \d+.\d+ and second group with pattern \d+.

Sample Regex 101 and test data


Import

@using System.Text.RegularExpressions;

(at the top of the page) in Blazor component (Example: <Your Page>.razor).

Append the capturing groups in the desired format.

@{
    Regex regex = new Regex("^(\\d+.\\d+):(\\d+)$");
    var match = regex.Match(labels.Ring_Position["1-03"]);

    string result = $"{match.Groups[1]} mm - {match.Groups[2]} °C";
            

    <div class="ring-Details" style="font-weight: lighter; font-size: small;">
        @result
    </div>
}

You can also write the logic for capturing value with regex into a method instead of code block.

Upvotes: 1

Related Questions