0

How do you access the json object using fetch in Node.Js?

I can fetch the json and print everything to console.log with no problem, but everything I have tried to get specific values from the json are not working. Can anyone point me in the right direction?

fetch('https://webhostapp.com/example.json')
.then(res => res.json())
.then(json => console.log(json)) //this prints everything correctly

//this is an example of the json
//How can I get the value of "1": "n111" for example?

{
"1": {
"Question": 1,
"n111": "Three men have just rode into town and haven't checked in with 
your office to declare if they have any weapons or not. Do you want to 
search them?",

},
"2": {
"Question": 2,
"n111": "Word has it that the Saloonkeeper’s card games are rigged.  Do 
you want to investigate to check if the decks are marked?",

}
}
Steven
  • 149
  • 1
  • 10
  • Where you currently do `console.log(json)`, instead do `console.log(json[1].n111)` – apsillers Jun 04 '19 at 17:42
  • > everything I have tried to get specific values from the json are not working ? Can you explain that? – Computer's Guy Jun 04 '19 at 17:42
  • @Steven it's not clear that the listed duplicate will solve you're problem. Many people also have issues like this because of async issues — trying to access the JSON outside the `then()` callback. You should show where you are trying to access the data (i.e. show the code that fails) if the link didn't help. – Mark Jun 04 '19 at 17:51
  • @apsillers Thanks that does output the right value but how would I assign that to a variable instead of just printing to console? – Steven Jun 04 '19 at 18:20
  • See https://stackoverflow.com/q/23667086/710446 and https://stackoverflow.com/q/14220321/710446. The main problem is timing: you can store it in a variable, but it will be done *chronologically after* the code outside the `then` callback – apsillers Jun 04 '19 at 18:22
  • Thanks, using those links I was able to assign a json value to a string...I was wondering if you know anything about actions on google, because my next question is in how to use that variable in an ssml response, it seems the timing is off once again https://stackoverflow.com/questions/56450332/how-to-wait-for-this-fetch-json-request-before-proceeding-to-the-welcome-intent – Steven Jun 04 '19 at 19:45

0 Answers0