How can I fetch a local JSON file that is in my directory?
the JSON file looks like this:
[
{
"name": "Sara",
"id": 3232
},
{
"name": "Jim",
"id": 2342
},
{
"name": "Pete",
"id": 532532
}
]
If I have the json information inside the same file I'm trying to use it, it works beautifully, but if I want to bring it in, I can't for the life of me get it to work and it keeps reading it as undefined.
here is what I have
getData() {
var json_data = require('../services/contributors.JSON');
for (var i in json_data){
console.log('Name: ' + json_data[i]["name"])
}
}
Can you see what I'm doing wrong? I'm trying to get this into react so maybe react works differently? I don't know. Any help will be appreciated. Thank you!
With the fetch API we need to call the json () function which reads the response to the completion. This also returns a promise, so we need to chain a new then method to get the JSON data that we want. Even though we are fetching the data from a file, we do the exact same thing when fetching data from an URL.
Example: Fetching data from a local JSON file in React Native. Step 1: Install react-native-fs using the following command: Note: If you are getting errors like Attempt to get length of null array EUNSPECIFIED then in the android manifest file add the following code.
if your json is inside public folder, so just write “filename.json” without “public/” word Here is my code if you need that: fetch ("/levels.json") .then (r => r.json ()) .then (json => { this.levels=json; }, response => { console.log ('Error loading json:', response) });
Let’s get started fetching our weather data. We will be using a simple JSON file for fetching the data. Copy the JSON content in a file called weather.json. Add the file into the root of the public folder of your project. Change the code in the script section in Weather.json to look like this: We have created a variable called weatherDataList.
Use fetch
fetch("../services/contributors.JSON")
.then(res => res.json())
.then(data => console.log(data))
I hope this helps
After series of hours trying to understand some comments here, I found out that the public folder is in the Root folder of the React app and not somewhere else because I was busy searching for a public folder that was not missing.
So for anyone and newbies like us still wondering where the public folder is, Its located rightly in your project folder under the "Node_Modules" folder
Afterwards, I used the following code:
useEffect(() => {
fetch('data.json')
.then(response => response.json())
.then((json) => setData(json))
}, [])
and viola, my json files were fetched !
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With