0

I am trying to read a JSON file and set a value based on what is read.

Here is what my leaves.json looks like:

{
    "Button_1": {
        "text": "Github",
        "link": "https://github.com/"
    },
    "Button_2": {
        "text": "LinkedIn",
        "link": "https://www.linkedin.com/"
    }
}

Here is the JSON reading code:

var buttons_json = fetch('./leaves.json')
    .then(response => response.json())
    .then(data => console.log(data))
    .catch(error => console.log(error));

I am unable to pull a value from the JSON object in memory, it tells me the value is undefined. For example:

console.log(buttons_json["Button_1"]["text"]);

Is undefined. You can see the console output here giving us undefined, but the JSON Object is properly read. Any ideas?

enter image description here

Seltonu
  • 95
  • 1
  • 9
  • `buttons_json` is a promise. You'll need to access the properties on `data`, *inside* the `.then()` callback. – Bergi Aug 19 '21 at 23:34
  • @Bergi hello! sorry I'm not too familiar with javascript, I'm not sure what this means. How would I go about this? – Seltonu Aug 19 '21 at 23:47
  • Change your code to `.then(data => console.log(data["Button_1"]["text"]))`. If you actually need to do something else with the values than logging it, it still needs to go inside that callback. I would recommend to familiarise yourself with the concepts of callbacks and promises if you want to develop javascript. – Bergi Aug 19 '21 at 23:50

0 Answers0