Dan Savage Dan Savage - 11 months ago 55
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 Source

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.


is the right way to do it. While


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


is a valid Json String.