Search code examples
javascriptjsonobjectundefined

Reading a JSON file in JavaScript "Undefined" object


I have created a JSON file with an object in it and I am trying to access the specific elements of the object. Although I get the object when I try to get the specific value I get "undefined". Any idea what is the problem here?

Here is my parameters.json file

{"employee": { "name": "sonoo", "salary": 56000, "married": true  }}

And Here is how I retrieve it from my JS file

fetch("parameters.json")
        .then(function(resp){
            return resp.json();
        })
        .then(function(data){
            console.log(data);
            
            console.log(data.name);
        })

Here is what I see in the console : 1


Solution

  • You should be able to see it from the screenshot, the path is data.employee.name not data.name.

    Try this:

    fetch("parameters.json")
            .then(function(resp){
                return resp.json();
            })
            .then(function(data){
                console.log(data);
    
                console.log(data.employee); // Whole employee
    
                console.log(data.employee.name); // Employee name
    
                console.log(data.name); // Undefined as it does not exist
            })