【问题标题】:Unexpected token u in JSON at position 0 when trying to access a field of JSON尝试访问 JSON 字段时,JSON 中位置 0 的意外标记 u
【发布时间】:2018-03-15 23:45:55
【问题描述】:

以下是我收到的 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 中位置 0 处的意外标记 u 在 JSON.parse() 处

当我使用resp.responses

我哪里错了?

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

【问题讨论】:

标签: javascript json signalr


【解决方案1】:

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

【讨论】:

  • 你能补充一些解释吗?之前出了什么问题,你做了什么来解决它。这被标记为低质量答案
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 2016-09-21
    • 1970-01-01
    • 2019-08-30
    • 1970-01-01
    • 2016-09-04
    • 2019-11-21
    • 2018-08-01
    • 1970-01-01
    • 2022-07-31
    相关资源
    最近更新 更多