添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接

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.

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.

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.

super(props); this.state = { stringData: '["VALUE1", "VALUE2", "VALUE3", "VALUE4", "VALUE5"]' super(props); this.state = { stringData: '["VALUE1", "VALUE2", "VALUE3", "VALUE4", "VALUE5"]' render() { // Parsed valued from string const valuesArray = JSON.parse(this.state.stringData); return ( <h3>Using local JSON file Array</h3> {valuesArray.map(item => { return <li>{item}</li>; export default Example1;

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.

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.

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