1

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>
Yong Shun
  • 35,286
  • 4
  • 24
  • 46
Guru
  • 47
  • 6

1 Answers1

1

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.

Yong Shun
  • 35,286
  • 4
  • 24
  • 46
  • 2
    thank you so much! code works with one small change to get perfect expected result. Change : string result = $"{match.Groups[1]} mm - {match.Groups[2]} °C"; – Guru Jul 01 '22 at 06:18