Answer the question
In order to leave comments, you need to log in
How to load local JSON in React?
Good day to all! I have a task to load data into React from a local .json file. I'm trying to check through the console on the local server and the import does not work and the error constantly crashes. Tried to google the solution but couldn't find a suitable answer to my question.
Below is the code of the json file itself and after it the code app.js React where I'm trying to implement everything
{
"result": [
{
"_id": "611e5bee6dbecd9b57cd7244",
"author_firstName": "Ангелина",
"author_lastName": "Пастернак",
"title": "Августина и Степан",
"city": "Санкт-Петербург",
"year": 2021
},
{
"_id": "611e5beea040b02068815775",
"author_firstName": "Ангелина",
"author_lastName": "Пастернак",
"title": "Армии племен пустыни",
"city": "Москва",
"year": 2020
}
]
}
import logo from '../../logo.svg';
import './App.css';
import data from '../utils/data.json';
function App() {
const result = JSON.parse(data);
console.log(result);
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>
Edit <code>src/App.js</code> and save to reload.
</p>
<a
className="App-link"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
>
Learn React
</a>
</header>
</div>
);
}
export default App;
Answer the question
In order to leave comments, you need to log in
So React is not responsible for this. This is a task for the used collector, you need to look in it.
What assembler is used?
If it was created through CRA (Webpack is there), then everything is set up there. It will be imported already as an object, JSON.parse() does not need to be done, this will cause a SyntaxError.
And by the way, yes, but what is the error? It usually contains half the answer to the question.
In the file where the JSON is stored:
const variable = {
"result": [
{
"_id": "611e5bee6dbecd9b57cd7244",
"author_firstName": "Ангелина",
"author_lastName": "Пастернак",
"title": "Августина и Степан",
"city": "Санкт-Петербург",
"year": 2021
},
{
"_id": "611e5beea040b02068815775",
"author_firstName": "Ангелина",
"author_lastName": "Пастернак",
"title": "Армии племен пустыни",
"city": "Москва",
"year": 2020
}
]
}
export default variable;
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question