简体   繁体   English

JSON字段未定义(JavaScript)

[英]JSON Fields are Undefined (Javascript)

I'm getting JSON from a servlet and turning the responseText into a JSON object by using JSON.parse(). 我从Servlet获取JSON,并使用JSON.parse()将responseText转换为JSON对象。 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. Chrome Developer Tools将JSON对象显示为具有所需的数据,但是当我实际尝试访问它时,我只会得到一堆“未定义”的数据。

Am I not interpreting the data correctly? 我不能正确解释数据吗?

Screenshot of Chrome Developer Tools: Chrome开发者工具的屏幕截图: 调试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. 屏幕快照中显示的jsonData作为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()? 如果您从服务器获取json,那么为什么要使用json.parse()? you should directly use the data as a json. 您应该直接将数据用作json。

JSON.parse() is used to parse string into JSON. JSON.parse()用于将字符串解析为JSON。 i undertand the response from the server is already a JSON which can used directly without further parsing. 我理解服务器的响应已经是一个JSON,可以直接使用它而无需进一步分析。

and as a way of troubleshooting you can use console.log to print the object. 作为故障排除方法,您可以使用console.log来打印对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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