Live Chat Icon For mobile
Live Chat Icon

How do I read a JSON file in Blazor WebAssembly?

Platform: Blazor| Category : Web API, General

To read a JSON file in Blazor WebAssembly, you can utilize the HttpClient class along with the GetFromJsonAsync() method.  

Follow these steps to achieve that: 

To proceed, create or load a JSON file in the wwwroot folder. As an example, I have created a basic employee.json file and will read its values within a Razor component. 

[wwwroot/employee.json]

[{"id": "emp1"}, {"id": "emp2"}, {"id": "emp3"}]

[Index.razor]

@page "/"
@inject HttpClient Http

@if (employees == null)
{
    <p>Loading...</p>
}
else
{
    @foreach (var employee in employees) 
    { 
        <p>Employee ID: @employee.Id</p>
    }
}


@code {
    private Employee[] employees;

    protected override async Task OnInitializedAsync()
    {
        employees = await Http.GetFromJsonAsync<Employee[]>("employee.json");
    }

    public class Employee
    {
        public string Id { get; set; }
    }
}

Refer to this documentation for more details.

Share with

Related FAQs

Couldn't find the FAQs you're looking for?

Please submit your question and answer.