Skip to content

Contact sales

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

Parse JSON Data in React.js

Aug 3, 2020 • 10 Minute Read

Introduction

In front end development, JSON data is not only vital, but almost inevitable. React developers heavily interact with JSON data and hence, knowledge on how to read, parse and manipulate it is very vital. JSON data can come from many sources but the most common are third party APIs and external data files.

In this guide, you will explore how to parse JSON data in React.js. It is assumed that you have a good foundational understanding of JSON and at least beginner proficiency in React.js.

JSON Data in React.js Development

According to Mozilla, "JSON is a is a standard text-based format for representing structured data based on JavaScript object syntax." It's completely language independent, which makes it widely used in the development world. It's primarily used to send data between apps and servers.

Set Up Sample App

Open your terminal and run these commands to create a basic React app.

      npx create-react-app react-json

cd react-json

npm start
    

Source JSON Data

To follow the example in this guide, you will fetch data from TMDB The Movie Database. You will need to set up a user account to obtain an API Key.

Parsing JSON in React

TMDB provides you with a list of movies, TV shows, and actors and their images in JSON format. You will need to parse through this data and show different genres of movies or TV shows in your app. For fetching data, you will use Axios, a library that facilitates making HTTP requests to external sources, in this case TMDB API. To install Axios, run the following command on your terminal.

      npm install axios
    

Navigate to your App.js file and paste the sample code below.

      import React, {Component} from 'react';
import axios from 'axios'

class App extends Component{
  constructor(props) {
    super(props);
    this.state =({
      movies: []
    })
  }
  componentDidMount() {
    let url = "https://api.themoviedb.org/3/discover/movie?api_key=abcdef123&sort_by=popularity.desc&page=1"
    axios.get(url)
        .then(response => {
          console.log(response.data.results)
            this.setState({
                movies: response.data.results
            })
        })
        .catch(error => {
          console.log(error)
        })
  }

  render() {
    return (
        <div>
        </div>
    );
  }

}

export default App;
    

You will first initialize movies state, which holds data coming from TMDB API. Next, you will use componentDidMount() which is a React lifecycle method. This lifecycle method is called immediately and the component is mounted. You can find out more about this here.

Inside this method, you will use Axios to fetch data from the TMDB API. Ensure you have a valid API key. The URL should fetch a list of popular movies from TMDB database. Set the movies state with the results from the API. Go to https://localhost:3000 in your browser and check for data in the console tab. If there's no data you might need to run the command npm run start or refresh your browser.

Here is sample data from the API.

      {
	"page": 1,
	"results": [{
			"poster_path": "/e1mjopzAS2KNsvpbpahQ1a6SkSn.jpg",
			"adult": false,
			"overview": "From DC Comics comes the Suicide Squad, an antihero team of incarcerated supervillains who act as deniable assets for the United States government, undertaking high-risk black ops missions in exchange for commuted prison sentences.",
			"release_date": "2016-08-03",
			"genre_ids": [
				14,
				28,
				80
			],
			"id": 297761,
			"original_title": "Suicide Squad",
			"original_language": "en",
			"title": "Suicide Squad",
			"backdrop_path": "/ndlQ2Cuc3cjTL7lTynw6I4boP4S.jpg",
			"popularity": 48.261451,
			"vote_count": 1466,
			"video": false,
			"vote_average": 5.91
		},
		{
			"poster_path": "/lFSSLTlFozwpaGlO31OoUeirBgQ.jpg",
			"adult": false,
			"overview": "The most dangerous former operative of the CIA is drawn out of hiding to uncover hidden truths about his past.",
			"release_date": "2016-07-27",
			"genre_ids": [
				28,
				53
			],
			"id": 324668,
			"original_title": "Jason Bourne",
			"original_language": "en",
			"title": "Jason Bourne",
			"backdrop_path": "/AoT2YrJUJlg5vKE3iMOLvHlTd3m.jpg",
			"popularity": 30.690177,
			"vote_count": 649,
			"video": false,
			"vote_average": 5.25
		},
		{
			"poster_path": "/hU0E130tsGdsYa4K9lc3Xrn5Wyt.jpg",
			"adult": false,
			"overview": "One year after outwitting the FBI and winning the public’s adulation with their mind-bending spectacles, the Four Horsemen resurface only to find themselves face to face with a new enemy who enlists them to pull off their most dangerous heist yet.",
			"release_date": "2016-06-02",
			"genre_ids": [
				28,
				12,
				35,
				80,
				9648,
				53
			],
			"id": 291805,
			"original_title": "Now You See Me 2",
			"original_language": "en",
			"title": "Now You See Me 2",
			"backdrop_path": "/zrAO2OOa6s6dQMQ7zsUbDyIBrAP.jpg",
			"popularity": 29.737342,
			"vote_count": 684,
			"video": false,
			"vote_average": 6.64
		}
	]

}
    

After fetching the data, you'll need to parse the JSON formatted data and display it in your app. For this approach, you will use simple Bootstrap card components. React Bootstrap provides Bootstrap components for React apps. Run npm install react-bootstrap bootstrap in your terminal. Finally, add the sample code below in your app.js file.

      import React, {Component} from 'react';
import axios from 'axios'
import 'bootstrap/dist/css/bootstrap.min.css';
import {Button, Card, Col, Row} from "react-bootstrap";


class App extends Component{
  constructor(props) {
    super(props);
    this.state =({
      movies: []
    })
  }
  componentDidMount() {
    let url = "https://api.themoviedb.org/3/discover/movie?api_key=b1422e7b80cff3571090be90e6544244";
    axios.get(url+"&sort_by=popularity.desc&page=1")
        .then(response => {
          console.log(response.data.results)
            this.setState({
                movies: response.data.results
            })
        })
        .catch(error => {
          console.log(error)
        })
  }

  render() {
    return (
        <Row>
            <Col>
                <Card style={{ width: '18rem' }}>
                    <Card.Img variant="top" src=""/>
                    <Card.Body>
                        <Card.Title>Card Title</Card.Title>
                        <Card.Text>
                            Some quick example text
                        </Card.Text>
                        <Button variant="primary">Go somewhere</Button>
                    </Card.Body>
                </Card>
            </Col>
        </Row>
        )
      }
}
export default App;
    

Now that you have your card component set, you will need to parse the JSON data in your movies state and set selected fields inside your card. You will use a nifty JavaScript method called map(). This method enables you to iterate over movies state and get the values you need for the fields. Remember your movies state holds your JSON data.

Add the sample code below to your app.js file.

      import React, {Component} from 'react';
import axios from 'axios'
import 'bootstrap/dist/css/bootstrap.min.css';
import {Button, Card, Col, Row} from "react-bootstrap";


class App extends Component{
  constructor(props) {
    super(props);
    this.state =({
      movies: []
    })
  }
  componentDidMount() {
    let url = "https://api.themoviedb.org/3/discover/movie?api_key=b1422e7b80cff3571090be90e6544244";
    axios.get(url+"&sort_by=popularity.desc&page=1")
        .then(response => {
          console.log(response.data.results)
            this.setState({
                movies: response.data.results
            })
        })
        .catch(error => {
          console.log(error)
        })
  }

  render() {
      const { movies } = this.state;
      return (
        <Row>
            {movies.map((movie, index) => (
                <Col key={index} sm={4} md={4} lg={3}>
                    <Card style={{ width: '18rem' }}>
                        <Card.Img variant="top" src={"http://image.tmdb.org/t/p/w300//"+movie.poster_path} />
                        <Card.Body>
                            <Card.Title>{movie.title}</Card.Title>
                            <Card.Text>
                                {movie.overview}
                            </Card.Text>
                        </Card.Body>
                    </Card>
                </Col>
                )
            )}
        </Row>
    )
  }
}
export default App;
    

Just like Bootstrap, React Bootstrap enables you to wrap your content inside rows and columns. The map function iterates over your movies state and passes selected values inside your card component. Notice the key={index} which tracks your current index inside your map function. Check your browser and you will see multiple cards of the most popular movies from the TMDB API.

Conclusion

You have now learned how to parse JSON data using React.js. The skill gained is most useful for developers who hold job positions such as React developer and front end engineer. To further build on this skill, you can pursue advanced concepts such as code splitting through dynamic imports. This comes in handy when you are looking to increase code performance.