8

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 value) to make it look like a form.

I am looking for the best way to do this. Do I need to parse? Do I need to use a map function? I am new to React so please show me solution with code. I've seen other questions similar to this but they include a lot of other code that I don't think I need.

Example of my code: test.json

{"person": {
  "name": "John",
  "lastname": "Doe",
  "interests":
  [
    "hiking",
    "skiing"
  ],
  "age": 40
}}

test.js

import React, {Component} from 'react';

class Test extends Component {
    render () {
      return (

           ) 
      }
};

export default Test;

I need code that lets me import from json and code inside component that displays ALL fields.

4
  • 1
    You need to include more info. From where do you want to get this json? From a local file? From asynchro http request? You want to display keys or values? Or both? Commented Jul 10, 2017 at 18:39
  • I want to get json from a local file and I want to display both keys and values Commented Jul 10, 2017 at 18:48
  • "import from json" do you have static file available at compile time? If yes and you are using webpack 2 import json from './path/to/file.json' would suffice. For webpack 1 you'll need to include json-loader for *.json file types. Commented Jul 10, 2017 at 18:55
  • As of "displays ALL fields" - this is too broad. Display how? <pre>{JSON.stringify(json, null, 2)}</pre> is enough? Commented Jul 10, 2017 at 18:56

6 Answers 6

16

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

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

class Test extends Component {
  render () {
    const elem = test.person;
    return (
     <ul>
       {Object.keys(elem).map((v, i) => <li key={i}>{v} {test[v]}</li> )}
     </ul>
    )
  }
};

export default Test;
Sign up to request clarification or add additional context in comments.

Comments

8

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 ...

import React, {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 });  
   });
}
class Test extends Component {
    console.log(this.state.items);
    render () {
      return (

           ) 
      }
};

export default Test;

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

Comments

1

Use JSON.parse(json) Example:

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

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

Comments

0

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}`;

export function fetchData(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.

3 Comments

Is axios for local files? Or just http requests? I am using a local file
Yes it can be local file and a remote request. In here you can just switch
switch from const root_url = http://api.jsonurl&appid=${api_key}; to './file.json'
0
  • 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})
    })
 }
 

Comments

0

If you're loading a file over HTTP, then you can use the built-in window.fetch() function (in browsers for the last few years, see Mozilla's developer pages for compatibility support).

fetch("https://api.example.com/items")
  .then(res => res.json())

The React docs explain some other ways of doing Ajax requests (i.e. requests from within an already-loaded web page).

If your JSON is in a local file, then just import it, as others have explained:

import test from 'test.json';

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.