Skip to content

Contact sales

By filling out this form and clicking submit, you acknowledge our privacy policy.

Get JavaScript Objects from a JSON File

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

Sep 23, 2020 • 4 Minute Read

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

      {
  "data": {
    "test1": {
      "name": "test123",
      "surname": "surname123"
    },
    "test2": {
      "name": "test456",
      "surname": "surname456"
    },
    "test3": {
      "name": "test789",
      "surname": "surname789"
    }
  }
}
    

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.

      import React, { Component } from "react";
// Import local JSON file
import Data from "./data";

export class Example1 extends Component {
  render() {
    return (
      <>
        <div>
          <h3>Using local JSON file</h3>
          {Object.keys(Data.data).map((item, i) => (
            <li key={i}>
              <span>Key name : {item}</span>
            </li>
          ))}
        </div>
      </>
    );
  }
}

export default Example1;
    

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

      import Data from "./data";
    

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

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

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.

      componentDidMount() {
    fetch("https://jsonplaceholder.typicode.com/users")
      .then(res => res.json())
      .then(
        result => {
          this.setState({
            data: result
          });
        },
        error => {
          console.log(error);
        }
      );
}
    

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.

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

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.

      render() {
    return (
      <>
        <div>
          <h3>Using API call</h3>
          {this.state.data &&
            this.state.data.length > 0 &&
            this.state.data.map((item, i) => (
              <li key={i}>
                <span>Email : {item.email}</span>
              </li>
            ))}
        </div>
      </>
    );
}
    

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.