Skip to content Skip to sidebar Skip to footer

React - Load All Data From Json Into Component

I am using React and trying to load data into my component from a local json file. I am trying to print all information, including the 'name' in a name:value pair (not just the val

Solution 1:

If your json is stored locally, you don't have to use any library to get it. Just import it.

importReact, {Component} from'react';
import test from'test.json';

classTestextendsComponent {
  render () {
    const elem = test.person;
    return (
     <ul>
       {Object.keys(elem).map((v, i) => <likey={i}>{v} {test[v]}</li> )}
     </ul>
    )
  }
};

exportdefaultTest;

Solution 2:

The first important question to care about is how you want to get this JSON, if I understood your problem very well it's a local JSON file. So you need to run a local server inside your app to get these values.

I'd recommend the live-server, made in node.js.

After that you can use axios to fetch data and then ...

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

constructor (props) {
   this.state = {
         items: [],
   }
   axios.get('http://localhost:8080/your/dir/test.json') 
    .then(res => {
        this.setState({ items: res.data });  
   });
}
classTestextendsComponent {
    console.log(this.state.items);
    render () {
      return (

           ) 
      }
};

exportdefaultTest;

I've already put a console.log before render to show your object, and after that do whatever you want!

Solution 3:

Use JSON.parse(json) Example:

JSON.parse(`{"person": {
    "name": "John",

    "lastname": "Doe",
    "interests": [
        "hiking",
        "skiing"
    ],
    "age": 40
}}`);

Solution 4:

Hi the best solution to this is using Axios.

https://github.com/mzabriskie/axios

Try look at their API its very straightforward.

And yes, you might need a map function to loop the parsed data.

I have a sample code here, which I used Axios.

import axios from'axios';
const api_key = 'asda99';
const root_url = `http://api.jsonurl&appid=${api_key}`;

exportfunctionfetchData(city) {    //export default???const url = `${root_url}&q=${city},us`;
  const request = axios.get(url);
}

request is where you get your parsed data. Go ahead and play with it

Heres another example using ES5

componentDidMount: function() {
    var self = this;

    this.serverRequest =
      axios
        .get("http://localhost:8080/api/stocks")
        .then(function(result) {
          self.setState({
            stocks: result.data
          });
        })

  },

by using the 2nd one. you stored the stocks as a state in here. parse the state as pieces of data.

Solution 5:

  • After http://localhost:3001/ you type your directory of JSON file: Mydata.json is my JSON file name, you type your file name: Don't forget to import axios on the top. *

componentDidMount() {
    axios.get('http://localhost:3001/../static/data/Mydata.json')
      .then(response => {
      console.log(response.data)
      this.setState({lists: response.data})
    })
 }
 

Post a Comment for "React - Load All Data From Json Into Component"