0

Hi I would like to know what is best way to fetch JSON objects from a local file which is in a below format to render list of Key value airs from those JSON list. I tried to import file as mentioned below but it goes in vain. I want to know how to fetch those key value pairs form local json file to display using jsx. any leads would be appreciated. for instance if i want to display "John got calls from the United states at 12.20 pm". Where John is passed as name ID under Calls,location under States and so on.

{"Calls":[there are list of key values pairs
],
"States":[there are a list of key value pairs],
"time:[list of key value pairs]"} 

React code:

import jsonData from "./example.json";

const loadData = () => JSON.parse(JSON.stringify(jsonData));

constructor() {
    super();
    this.state = {
      userList: []
    };
   }

   componentWillMount() {
    axios.get('./example.json') // JSON File Path
      .then( response => {
        this.setState({
        userList: response.data
      });
    })
    .catch(function (error) {
      console.log(error);
    });
   }

   render() {
  const usersList = this.state.userList;
  let usersListBlock = '';

  if(usersList.length > 0) {
    usersListBlock = usersList.map( obj => {
      return (
        <Usercard key={obj.id} id={obj.id} id={obj.number} name={obj.name} />
            )
    })
   }

   return(
    <div className="row container">
        {usersListBlock}
    </div>
   )
}
prb_cm
  • 117
  • 1
  • 4
  • 13

2 Answers2

0

You can directly use json file by importing and then you can use json object directly or set it in state. Import Json file like you have already done

import jsonData from "./example.json";

and then in set it in state or use directly

componentWillMount() {
    this.setState({userList:jsonData })

   }
0

I had the same problem, try to save JSON file in public folder and just call it with axios.get('example.json'), it worked for my just fine.