Reputation:
(It's actually for an assignment)
Hi, For hours I tried to solve my problem, I found some solutions, but it wasn't really what I wanted, and from my code I'm always hitting the same wall. thank you.
So I have a JSON file and a javascript file :
In my JSON file I have simple array of list of URL
{
"myUrlDatabase":[
"https://www.francebleu.fr/emissions/ca-va-dans-le-bon-sens-en-poitou/poitou/quel-est-l-impact-du-changement-climatique-sur-les-migrations-d-oiseaux-marins",
"https://www.terrafemina.com/article/environnement-pourquoi-2021-est-une-annee-cruciale-pour-agir_a357981/1",
"https://www.franceinter.fr/monde/rechauffement-climatique-2020-est-l-annee-la-plus-chaude-jamais-enregistree-en-europe",
//more url
]}
I would like to access it in my javascript file, from what I have seen, I should use the fetch function, I followed a code on internet
fetch('/Data/url.json').then(function (response){
return response.json();
}).then(function (obj){
console.log(obj);
});
Indeed it print the file. but how can I make a var of the array ?
I would like later to use it in a random function
Math.randon() * {JSONFILE.length}
Upvotes: 1
Views: 64
Reputation: 122906
fetch
delivers a Promise
, so you have to use a (callback) lambda to use its result. Here's an example for that, mocking your random function for the keys of the result.
const postFetch = data => {
if (!data.error) {
const allKeys = Object.keys(data.results);
const someKey = Math.floor(Math.random() * allKeys.length);
console.log(`A pseudo random result => ${allKeys[someKey]}: ${
data.results[allKeys[someKey]]}`);
console.log(`The original json: ${JSON.stringify(data.results)}`);
} else {
console.log(`an error occured: ${data.message}`);
}
}
fetch("https://api.sunrise-sunset.org/json?lat=53.22179255&lng=6.5582453664798")
.then(r => r.json())
.then(postFetch)
// ^ continue with the resulting object within your own function
.catch(error => ({
error: true,
url,
message: error.message
}));
Upvotes: 1
Reputation: 1447
You can use the JSON.parse()
method to transform json into a JavaScript data structure.
Similar to your example:
// your response
const jsonInfo = "{ \"propArr\": [ \"string1\", \"string2\", \"string3\" ] }"
// use the parse() method
const getTheArray = JSON.parse(jsonInfo).propArr;
console.log(getTheArray);
Or if your data is already an object just do const whatIWant = receivedData.theArrayIWant
and you'll have the whatIWant
array.
Upvotes: 0
Reputation: 1149
You can access nested properties within the parsed JSON simply as fields within the obj
parameter. The field which you want to access is myUrlDatabase
.
var array = obj.myUrlDatabase
console.log(array.length)
Upvotes: 1