Here's the scenario:
I have created a function that reads my JSON file and returns the value found at the end.
This is how my files are organized:
https://i.sstatic.net/TMeXVHNJ.png
Below is my script.js file:
async function readJSONFile(path) {
const [filePath, jsonPath] = path.split('|');
try {
const response = await fetch(filePath);
if (!response.ok) {
throw new Error(`Network response was not ok: ${response.statusText}`);
}
const jsonData = await response.json();
const keys = jsonPath.split('/');
let value = jsonData;
for (const key of keys) {
if (Array.isArray(value) && !isNaN(key)) {
value = value[parseInt(key)];
} else {
value = value[key];
}
if (value === undefined || value === null) {
return undefined;
}
}
return value;
} catch (error) {
console.error(`Failed to read JSON file: ${error}`);// There's an error
return undefined;
}
}
const path = 'Items.json|Data/taxValue';
readJSONFile(path).then(result => console.log(result)); // Should print 1.15
And here is my JSON file in case it is needed:
{
"Data": [
{
"taxValue": 1.15
}
],
"Fruits": [
{
"name": "apple",
"cost": 1.59,
"tax": true,
"itemId": 12345,
"ect...": 0
}
],
"Others": [
]
}
I expected to read the file but encountered an error,
'
script.js:25 Failed to read JSON file: TypeError: Failed to fetch
',I am unsure about how to fix this issue, which is why I am seeking help.