尝试访问JSON字段时,位于0的JSON中出现意外的令牌u

问题描述 投票:-1回答:2

以下是我收到的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

我哪里错了?

任何形式的帮助将不胜感激。谢谢。

javascript json signalr
2个回答
0
投票

好吧,基本上,如果resp是一个字符串,那么如果你做JSON.parse(resp.responses)将失败,因为responsesundefined

你只想要JSON.parse(resp).responses。这包含您需要的数组


1
投票

试试这个:createChart(JSON.parse(resp).responses);

© www.soinside.com 2019 - 2024. All rights reserved.