简体   繁体   中英

JSON Fields are Undefined (Javascript)

I'm getting JSON from a servlet and turning the responseText into a JSON object by using JSON.parse(). Chrome Developer Tools shows the JSON object as having the data that I want, but when I actually try to access it I just get a bunch of 'undefined's.

Am I not interpreting the data correctly?

Screenshot of Chrome Developer Tools: 调试JSON对象的输出

And briefly, my code to output the data:

        for (var i = 0, len = jsonObj.length; i < len; ++i) {
            // Setup the result...
            var resultRow = document.createElement("tr");
            resultsTable.appendChild(resultRow);            
            var result = jsonObj[i];

            // Name
            var coverCell = resultRow.insertCell(0);
            coverCell.innerHTML = result.name;
        }

jsonData as seen in the screenshot is passed into the output function as jsonObj.

The key you are trying to access seems to have the @ character at the front. Since the @ character is not a valid identifier and therefore you can't use dot-notation, you can retrieve the value by using bracket notation:

coverCell.innerHTML = result['@name'];

if you are getting json from the server then why are you using json.parse()? you should directly use the data as a json.

JSON.parse() is used to parse string into JSON. i undertand the response from the server is already a JSON which can used directly without further parsing.

and as a way of troubleshooting you can use console.log to print the object.

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