0

The following is the json that I am receiving:

{
"total": 5,
"responses": [{
    "gender": "Female",
    "age": 66
}, {
    "gender": "Male",
    "age": 52
}]
}

The following is the code I am using to receive and parse the 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();

In the console I am being able to see the entire JSON response like I showed above by doing console.log(JSON.parse(resp));

But I am getting the error

Unexpected token u in JSON at position 0 at JSON.parse ()

When I am using resp.responses

Where am I going wrong?

Any kind of help would be greatly appreciated. Thanks.

Steve Doson
  • 703
  • 4
  • 16
  • 34

2 Answers2

1

Try this : createChart(JSON.parse(resp).responses);

morgane1806
  • 75
  • 1
  • 5
  • 2
    Could you add some explanation? What went wrong before and what you did to fix it. This was flagged as a low quality answer – Huangism Mar 15 '18 at 16:13
0

Well, basically, if resp is an string, then if you do JSON.parse(resp.responses) will fail because responses is undefined.

You just want JSON.parse(resp).responses. This contains the array you need

Oscar Paz
  • 18,084
  • 3
  • 27
  • 42