简体   繁体   中英

Retrieving JSON values from var within a JSON

The below function is throwing me a TypeError and I'm trying to understand why. Bascially I have a JSON (var test) that is a JSON and I'm trying to access another var's (blogspotter) JSON data. For my script blogspotter needs to be a dynamic JSON. If I take the JSON found in blogspotter and copy it into static value (caseJSON) it works, but if I try to do it via a var (caseVAR) I get an error.

Any help would be much appreciated!

function stackerFlow (d) {    
var blogspotter = getAllowedIntervals ()   
   ///  getAllowedIntervals returns the exact JSON as found in test.caseJSON   

var test = {
  "caseJSON" : {"interval":{"start_month":12,"start_year":2014,"end_month":12,"end_year":2017}}
  "caseVAR" : blogspotter     
}

Logger.log (blogspotter)    /// returns a valid JSON
Logger.log(test.caseJSON.interval.start_month)  /// returns 12
Logger.log(test.caseVAR.interval.start_month)   //// throws an error - "TypeError: Cannot read property "start_month" from undefined.
}

I reworked your code a bit so I could run it easily. I added the getAllowedIntervals function so it returns the blogspotter as you said and added a comma before "caseVar". If you save my code in something like test.htm, open it in mozilla, open the console(click anywhere and choose "inspect element") and click on the stackerflow button you can see it runs fine:

<html>
<head>
    <script>
    function getAllowedIntervals() {
        return {"interval":{"start_month":12,"start_year":2014,"end_month":12,"end_year":2017}};
    }
    function stackerFlow () {    
        var blogspotter = getAllowedIntervals();
        var test = {
          "caseJSON" : {"interval":{"start_month":12,"start_year":2014,"end_month":12,"end_year":2017}},
          "caseVAR" : blogspotter     
        }

        console.log (blogspotter)    /// returns a valid JSON
        console.log(test.caseJSON.interval.start_month)  /// returns 12
        console.log(test.caseVAR.interval.start_month)   //// throws an error - "TypeError: Cannot read property "start_month" from undefined.
    }
    </script>
</head>
<body>
    <input type="button" onclick="stackerFlow()" value="stackerFlow"/>
</body>
</html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM