DEV Community

Cover image for Get JavaScript Objects from a JSON File
nikhil sharma
nikhil sharma

Posted on

Get JavaScript Objects from a JSON File

Introduction

JSON stands for JavaScript Object Notation.JSON is a lightweight format for storing and transporting data.JSON is often used when data is sent from a server to a web page.JSON is "self-describing" and easy to understand. 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 blog 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

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

{
"employees":{
"employee1": {"firstName":"John", "lastName":"Doe"},
"employee2": {"firstName":"Anna", "lastName":"Smith"},
"employee3": {"firstName":"Peter", "lastName":"Jones"}
}
}
Enter fullscreen mode Exit fullscreen mode

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 Sample extends Component {
  render() {
    return (
      <>
        <div>
          <h3>Using local JSON file</h3>
          {Object.keys(Data.employees).map((item, i) => (
            <li key={i}>
              <span>Key name : {item}</span>
            </li>
          ))}
        </div>
      </>
    );
  }
}

export default Sample;

Enter fullscreen mode Exit fullscreen mode

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

import Data from "./data";
Enter fullscreen mode Exit fullscreen mode

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.employees).map((item, i) => ())}
Enter fullscreen mode Exit fullscreen mode

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.

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);
        }
      );
}
Enter fullscreen mode Exit fullscreen mode

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>
      </>
    );
}
Enter fullscreen mode Exit fullscreen mode

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.

Hope ou enjoyed the blog post!!

Please feel free to like, save and comment your thoughts!!

Happy Reading!!!

Discussion (4)

Collapse
lukeshiru profile image
Luke Shiru • Edited on

A few tips based on your snippets:

  • If you want to loop over an object, you can use Object.entries instead, which is way better. Also, you should avoid using the index of an array as key, because the value needs to be unique, and if you update said list, then it will be key overlap. One last thing, try using function components instead of class components, even more so for components as simple as this, and take the data from props instead of directly from files:
export const Sample = ({ employees }) => (
    <>
        <div>
            <h3>Using local JSON file</h3>
            <ul>
                {Object.entries(employees).map(([key, value]) => (
                    <li key={key}>
                        <span>Key name: {value}</span>
                    </li>
                ))}
            </ul>
        </div>
    </>
);

// And then you use it like this: <Sample employees={Data.employees} />
Enter fullscreen mode Exit fullscreen mode
  • When working with fetch and promises, you can simplify your code greatly:
fetch("https://jsonplaceholder.typicode.com/users")
    .then(res => res.json())
    .then(setUsers)
    .catch(console.error);
Enter fullscreen mode Exit fullscreen mode
  • Your final snippet then, using the {JSON} Placeholder API, would look like this instead:
import { useEffect, useState } from "react";

export const Users = ({ users }) => (
    <div>
        <h3>Using API call</h3>
        <ul>
            {users?.map(({ id, email }) => (
                <li key={id}>
                    <span>Email: {email}</span>
                </li>
            ))}
        </ul>
    </div>
);

export const App = () => {
    const [users, setUsers] = useState([]);

    useEffect(
        () =>
            void fetch("https://jsonplaceholder.typicode.com/users")
                .then(res => res.json())
                .then(setUsers)
                .catch(console.error),
        [],
    );

    return <Users users={users} />;
};
Enter fullscreen mode Exit fullscreen mode

Cheers!

Collapse
sharma2288 profile image
nikhil sharma Author

Thanks for the suggestions and tips!! @lukeshiru

Collapse
jancizmar profile image
Jan Cizmar

Just a tip: You can specify a language in markdown so if you do:

```javascript
let hello = "it's highlighted"
Enter fullscreen mode Exit fullscreen mode

It's going to be highlighted:

let hello = "it's highlighted"
Enter fullscreen mode Exit fullscreen mode
Collapse
sharma2288 profile image
nikhil sharma Author

Thanks @jancizmar for tip!!