以下是我收到的json:
{
"total": 5,
"responses": [{
"gender": "Female",
"age": 66
}, {
"gender": "Male",
"age": 52
}]
}
以下是我用来接收和解析json的代码
// Declare a proxy to reference the hub.
$.connection.hub.url = 'https://www.url...';
var res = $.connection.resHub;
// Create a function that the hub can call to broadcast messages.
res.client.broadcastRes = function (resp) {
var now = new Date();
console.log(now.toLocaleTimeString(), 'signalR survey data received', JSON.parse(resp));
createChart(JSON.parse(resp.responses));
};
$.connection.hub.start();
在控制台中,我能够通过执行console.log(JSON.parse(resp));
看到整个JSON响应,就像我上面所示
但是我收到了错误
在JSON.parse()的位置0的JSON中出现意外的标记u
当我使用resp.responses
时
我哪里错了?
任何形式的帮助将不胜感激。谢谢。
好吧,基本上,如果resp
是一个字符串,那么如果你做JSON.parse(resp.responses)
将失败,因为responses
是undefined
。
你只想要JSON.parse(resp).responses
。这包含您需要的数组
试试这个:createChart(JSON.parse(resp).responses);