How to Read from Json File and Run a Loop to Get Json Data

Malshani Wijekoon
2 min readJan 15, 2023

--

As a first step we need to install node.js and create a new react project. For better coding install Visual Studio Code (You can choose any IDE which supports react.js).

Folder Structure

As you can see in the above picture create data.json and Loop.js files under src folder.

Add following code inside mentined files.

data.json

[
{
"name":"Casual",
"count":7
},

{
"name":"Annual",
"count":14
},
{
"name":"Sick",
"count":14
}
]

Loop.js

import React from "react";
import JsonData from './data.json';
import { useState, useEffect} from "react";

function Loop(){

const [leave, setLeave] = useState({
name:0,
casualCount:0,
annualCount:0,
sickCount:0
});

const [totalLeave, setTotalLeave] = useState({
totalAnnual: 0,
totalNonAnnual:0,
totalPercentage:0
});

useEffect(()=>{
JsonData.map(
(item)=>{
if (item.name === "Casual"){
leave.casualCount = item.count;
} else if(item.name === "Annual"){
leave.annualCount = item.count;
} else if (item.name === "Sick"){
leave.sickCount = item.count;
}
totalLeave.totalAnnual = leave.annualCount;
totalLeave.totalNonAnnual = leave.casualCount + leave.sickCount;
totalLeave.totalPercentage = (leave.annualCount/ (totalLeave.totalNonAnnual + totalLeave.totalAnnual)) * 100;
}
)
setLeave({ ...leave});
setTotalLeave({ ...totalLeave});
}, [])

return(
<div>
<h1>Annual - {totalLeave.totalAnnual}</h1>
<h1>Non Annual - {totalLeave.totalNonAnnual}</h1>
<h1>Annual Percentage - {totalLeave.totalPercentage}%</h1>
</div>
)
}

export default Loop;

App.js

import './App.css';
import Loop from './Loop';

function App() {
return (
<div>
<Loop/>
</div>
);
}

export default App;

Buid the app

npm run build
build the app

Start the application

npm start
start the app

Open the browser and go to http://localhost:3000 (This is according to the local server you used. Here I’m using 3000 port). You will see the output bellow.

Output

Browser

Download Code Here !

--

--