I'm going through my code and neatening it up to make it easier to understand. In my code, I parse the same JSON at different points to get different data from the JSON.
I want to create a function which I call, and pass a parameter and it will return the information from the JSON.
My JSON looks like this:
{
"Date": "11:10:02 28-02-19",
"Number1": 2031,
}
The function I am trying to use is this:
function dataJson(key) {
fetch("http://file/location/data.json?newversion") // supported in modern browsers.
.then(res => res.json()) // parses into JSON. Fails if given improper json
.then(data => {
return data.key;
})
}
and I am calling it within my script like:
dataJson(Date);
It should return 11:10:02 28-02-19
but I get the error
Uncaught ReferenceError: Date is not defined
And in VS Code it tells me that key
is declared but never read. When I have this in my script I would just use data.Date
and it would return what I want.
How do I call the function with a parameter and pass the parameter into the JSON parse to return the data I want?