Author avatar

Gaurav Singhal

Get JavaScript Objects from a JSON File

Gaurav Singhal

  • Sep 23, 2020
  • 4 Min read
  • 49,885 Views
  • Sep 23, 2020
  • 4 Min read
  • 49,885 Views
Web Development
Client-side Frameworks
React
Front End Web Development

Introduction

JSON is a file format widely used for static storage and app config management with any of the frameworks and data servers. Any JSON file contains the key-value pair separated by the comma operator. JavaScript objects are an integral part of the React app, so they need to get accessed from JSON files/data to be uses in components.

This guide will demonstrate how to get a JavaScript object from a JSON file or access it using a fetch() HTTP request.

Rendering Values from a JSON File

Any JSON data can be consumed from different sources like a local JSON file by fetching the data using an API call. After getting a response from the server, you need to render its value.

You can use local JSON files to do an app config, such as API URL management based on a server environment like dev, QA, or prod.

Create one sample JSON file as given below, and save it as data.json

1{
2  "data": {
3    "test1": {
4      "name": "test123",
5      "surname": "surname123"
6    },
7    "test2": {
8      "name": "test456",
9      "surname": "surname456"
10    },
11    "test3": {
12      "name": "test789",
13      "surname": "surname789"
14    }
15  }
16}
json

Now, if you want to render any of the key-value pairs from the JSON, the .map() function would be useful to iterate the objects; the example is below.

1import React, { Component } from "react";
2// Import local JSON file
3import Data from "./data";
4
5export class Example1 extends Component {
6  render() {
7    return (
8      <>
9        <div>
10          <h3>Using local JSON file</h3>
11          {Object.keys(Data.data).map((item, i) => (
12            <li key={i}>
13              <span>Key name : {item}</span>
14            </li>
15          ))}
16        </div>
17      </>
18    );
19  }
20}
21
22export default Example1;
jsx

In the above example, to use the local JSON file needs to be consumed using the import statement.

1import Data from "./data";
jsx

After that, you can access all the JSON data using Data in your component by using Object.keys() along with the .map() function.

1{Object.keys(Data.data).map((item, i) => ())}
jsx

Using a local JSON file in the React app is a common approach when you want to render some static data, maintain server config, etc.

Rendering JSON Objects from an API Call

You have seen the example where a local JSON file is used, but at the same time you may need to access JSON data from the server.

Most of the backend service is now compatible with JSON and returns the response data as JSON format. Thus, you need to manage JSON data such as objects and arrays from the server.

Implement the API call as demonstrated below.

1componentDidMount() {
2    fetch("https://jsonplaceholder.typicode.com/users")
3      .then(res => res.json())
4      .then(
5        result => {
6          this.setState({
7            data: result
8          });
9        },
10        error => {
11          console.log(error);
12        }
13      );
14}
jsx

To make the API call, you can use either fetch() or another third-party package called Axios. In the above example, the fetch() is used followed by the URL of the API.

One thing to notice is that when the response comes from the server, its format will change as JSON.

1.then(res => res.json())
jsx

Now, the response of the API will be JSON and stored into the component state called data.

After implementing the API call, you can access the JSON data for the rendering as below.

1render() {
2    return (
3      <>
4        <div>
5          <h3>Using API call</h3>
6          {this.state.data &&
7            this.state.data.length > 0 &&
8            this.state.data.map((item, i) => (
9              <li key={i}>
10                <span>Email : {item.email}</span>
11              </li>
12            ))}
13        </div>
14      </>
15    );
16}
jsx

Along with the state this.state.data, the additional function used is .map(), which iterates the array items from the state and renders them into the DOM.

Conclusion

JSON is a widely accepted format for data transition across the client and server, and most backend APIs send a response as JSON.

Your app should be well equipped to manage JavaScript objects from a JSON file. This guide will be useful to you to understand how to use JavaScript objects from the JSON file or how to get JSON from the server.