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 |
|
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 |
|
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 |
|
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.
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 |
|
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 |
|
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 |
|
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 |
|
Remember check your browser inspector to see console.log()
data.
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 |
|
Run your project
Run your project and it should render loaded JSON.
1 |
|
Example - https://dummyjson.com
A below example shows how you can load and show data from some RESTfull API.