Author avatar

Gaurav Singhal

Convert a JSON File to an Array in React

Gaurav Singhal

  • Oct 8, 2020
  • 6 Min read
  • 118 Views
  • Oct 8, 2020
  • 6 Min read
  • 118 Views
Web Development
Front End Web Development
Client-side Frameworks
React

Introduction

Usually JSON files contain an array, and it is necessary to map the array effectively so its objects' data gets consumed into the component. The source of the JSON file can be anything, either from a local JSON file or a network call. This guide will demonstrate how to get the JSON data as an array and parse it or access the JSON array from the local file.

Convert JSON to Array Using `json.parse()`

The JSON file usually contains one key prop representing the tree of the object inside the file content. If you want to use the JSON data along with the key, then the parse() function can be used.

The parse() function takes the argument of the JSON source and converts it to the JSON format, because most of the time when you fetch the data from the server the format of the response is the string.

1
JSON.parse(JSON_source)
jsx

Make sure that it has a string value coming from a server or the local source. If so, then the parse function will work.

To follow along with the example in this guide, create a state value with a string value that consists of an array of items.

1
2
3
4
5
6
constructor(props) {
    super(props);
    this.state = {
        stringData: '["VALUE1", "VALUE2", "VALUE3", "VALUE4", "VALUE5"]'
    };
}
jsx

The state variable called stringData has a string value that contains the array of items now. It would help if you used the function parse(), which converts string value to a JavaScript object.

1
const valuesArray = JSON.parse(this.state.stringData);
jsx

After parsing the value, it can be used for the rendering. Below is the complete example for the JSON parsing.

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
import React, { Component } from "react";

export class Example1 extends Component {
    constructor(props) {
        super(props);
        this.state = {
            stringData: '["VALUE1", "VALUE2", "VALUE3", "VALUE4", "VALUE5"]'
        };
    }

    render() {
        // Parsed valued from string
        const valuesArray = JSON.parse(this.state.stringData);

        return (
            <>
                <div>
                    <h3>Using local JSON file Array</h3>
                    <ul>
                        {valuesArray.map(item => {
                            return <li>{item}</li>;
                        })}
                    </ul>
                </div>
            </>
        );
    }
}

export default Example1;
jsx

After getting the values from the server, the parse() function has been used. The parse data as an array could be mapped using the function .map(), which iterates over the array of items.

Convert JSON to Array from Local File

It may be possible that the JSON file needs to get used from the local source, and it also may contain an array of items or objects.

To convert the array from the local JSON file to the JavaScript-based object, you can use the ES6 import statement to import the local JSON file and use it in the existing components.

Any JSON file can be imported from the local directory.

1
import Students from "./Students";
jsx

Here in the above import statement, the Students will represent the source of the JSON file, and you need to provide its path from where the JSON file exists into the project directory. Below is the sample Students.json file that you can use as demo.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
{
  "students": [
    {
      "name": "Student 1",
      "age": "22",
      "department": "Information Technology",
      "rollno": "123"
    },
    {
      "name": "Student 2",
      "age": "21",
      "department": "Computer Engineering",
      "rollno": "456"
    },
    {
      "name": "Student 3",
      "age": "23",
      "department": "Information Technology",
      "rollno": "789"
    }
  ]
}
json

After importing the JSON file from the local source, you will be able to use the source object. This is also used to extract the data, as shown below.

1
2
3
4
5
6
{Students.students.map((item, i) => (
    <tr key={i}>
        <td>{item.name}</td>
        <td>{item.department}</td>
    </tr>
))}
jsx

Students.students contains the different objects with the details about each student. But with the JSON object, there is an additional function called .map() used to map the array of objects from the source.

Below is the complete example of getting the JSON source and mapping the array of objects.

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
import React, { Component } from "react";
// Getting local JSON file
import Students from "./Students";

export class Example2 extends Component {
    render() {
        return (
            <>
                <div>
                    <table border="2">
                        <tbody>
                            <tr>
                                <th>Name</th>
                                <th>Department</th>
                            </tr>
                            // Mapping array of objects
                            {Students.students.map((item, i) => (
                                <tr key={i}>
                                    <td>{item.name}</td>
                                    <td>{item.department}</td>
                                </tr>
                            ))}
                        </tbody>
                    </table>
                </div>
            </>
        );
    }
}

export default Example2;
jsx

Both the ways of consuming JSON data and, more specifically, an array of items or objects gets integrated easily using parse() and map() functions.

Conclusion

JSON is a suitable file format for the data exchange between client and server, and contains the key-value pair as a string value. The JavaScript function parse() converts the string to a JavaScript object, and map() iterates through an array of objects.

1