Dan Savage Dan Savage - 2 months ago 13
JSON Question

Referring to JSON using variables

So I'm trying to improve the usability of a function which parses JSON

var r = JSON.parse(cb[0].ResponseTime);


However, when I create a variable called name and send it to this, I get

var r = JSON.parse(cb[0].name);
SyntaxError: Unexpected token u


How can I do this? Alternative method?

Answer

JSON.parse(jsonString) function takes a valid json string as argument, and throws an error if it does not recieve a valid json string.

for ex.

JSON.parse('{"hello":"bello"}')

is the right way to do it. While

JSON.parse("hello"); 

Should throw an error because "hello" is not a valid json string. So make sure that

cb[0].name

is a valid Json String.