Reputation: 139
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.
Upvotes: 8
Views: 28597
Reputation: 2249
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';
Upvotes: 0
Reputation: 645
componentDidMount() {
axios.get('http://localhost:3001/../static/data/Mydata.json')
.then(response => {
console.log(response.data)
this.setState({lists: response.data})
})
}
Upvotes: 0
Reputation: 41893
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;
Upvotes: 15
Reputation: 1995
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!
Upvotes: 8
Reputation: 274
Use JSON.parse(json) Example:
JSON.parse(`{"person": {
"name": "John",
"lastname": "Doe",
"interests": [
"hiking",
"skiing"
],
"age": 40
}}`);
Upvotes: 1
Reputation: 157
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.
Upvotes: 0