Skip to content

M05 - Load and parse JSON

Introduction

Many dynamic application loads data from the internet. There are two major methods for retrieving data from most web services: XML or JSON. Nowadays web are heavily using JSON to store and transfer data between apps and server side.

Small JSON example file

A following JSON data will be used in a below examples. JSON key highscores points to array of highscores with a name and a score fields. You can save it as a highscores.json file to your project.

highscores.json
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
{
"highscores": 
[
    { "name":"Jaakko Teppo","score":10000 },
    { "name":"Smith Fessel", "score":8000 },
    { "name":"Jones Bigss", "score":6000 },
    { "name":"Farren Goods", "score":4000 },
    { "name":"Milla Junes", "score":2000 }
]
}

JSON Server and data

You can use your own server to store JSON files or just install a JSON Server to your own computer, which helps you work with JSON when you are developing your application.

Create a new React app and store/save above highscores.json to your project folder.

1
npx create-react-app json-example-app

You can run JSON Server as a global server or just watch a one JSON file. Remember that create-react-app will use port 3000 as a default.

Watch a local file at port 3001

1
npx json-server --port=3001 --watch highscores.json

Open your browser and point it to http://localhost:3001/highscores addess. It should display a loaded JSON data. You can install for example JSONView plugin, if you are using Chrome.

Image 01

Note

Alternatively you can save JSON files to your project public folder and load it from there without JSON server.

Load and Parse JSON

Axios

You can use fetch or other 3th party libraries to load JSON data to your React application.

Install Axios to your project using a following npm command:

1
npm install axios

Note how Axios will be added to your project dependencies (package.json). Note that version numbers can be different.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
"dependencies": {
  "@testing-library/jest-dom": "^5.16.5",
  "@testing-library/react": "^13.3.0",
  "@testing-library/user-event": "^13.5.0",
  "axios": "^1.6.5",
  "react": "^18.2.0",
  "react-dom": "^18.2.0",
  "react-scripts": "5.0.1",
  "web-vitals": "^2.1.4"
},

Modify App.js and use Axios to load highscores.json and show it in your application. Note how you can use React Hooks effect to load data, when application starts.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import React, { useState, useEffect } from 'react'
import axios from 'axios'

function App() {
  const [highscores, setHighscores] = useState([]) 

  // use effect to load data
  useEffect(() => {
    console.log('effect')
    axios
      .get('http://localhost:3001/highscores')
      .then(response => {
        console.log('highscores loaded - a promise fulfilled')
        console.log(response.data)
        setHighscores(response.data)
      }).catch(err => {
        // Handle error
        console.log(err);
    });
  }, []) // load once, use => []

  // create li-elements from highscreo data
  const highscoreItems = highscores.map((highscore,index) =>
    <li key={index}>{highscore.name} : {highscore.score}</li>
  );

  // render loaded json data 
  return (
    <div className="App">
      <ul>
        {highscoreItems}
      </ul>
    </div>
  );
}

export default App;

Note

You can save your highscores.json file to your project public folder and load your JSON data from there. Note that now JSON is not served and you will need to find a highscores key from returned data!

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
// use effect to load data
useEffect(() => {
  console.log('effect')
  axios
    //.get('http://localhost:3001/highscores')
    .get('highscores.json')
    .then(response => {
      console.log('highscores loaded - a promise fulfilled')
      console.log(response.data)
      setHighscores(response.data.highscores)
    }).catch(err => {
      // Handle error
      console.log(err);
  });
}, []) // load once, use => []

Remember check your browser inspector to see console.log() data.

Image 03

async and await

You can also use async and await with axios to keep you code cleaner.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
async function fetchData() {
  try {
    let response = await axios.get('highscores.json');
    setHighscores(response.data.highscores);
  } catch (error) {
    console.log(error);
  }
}

useEffect(() => {
  fetchData();
}, []) // load once, use => []

Run your project

Run your project and it should render loaded JSON.

1
npm start

Image 02

Example - https://dummyjson.com

A below example shows how you can load and show data from some RESTfull API.

Read more