Getting "Unexpected token ':'" from a simple JSON string

var info = eval(req.responseText);

// req.responseText = {id: 2, title: "KVillains", description: "KVillains are an American punk rock band from Knoxville, TN and signed with Silverstone Records in Los Angeles, CA.", url: "http://kvillains.com"}

alert(info.title[0]._text);

The JSON is pulled in just fine, but when I try to access the information I get the unexpected token error.

Any ideas?

Well this would result in the title being shown - does that help?


req = {};
req.responseText = {id: 2, title: "KVillains", description: "KVillains are an American punk rock band from Knoxville, TN and signed with Silverstone Records in Los Angeles, CA.", url: "http://kvillains.com"}

info = req.responseText;
alert(info.title);

I get “undefined” with the code above.

I found doing the eval() with parenthesis properly builds the object.

var info = eval('(' + req.responseText + ')');

When it comes to converting JSON content, I highly recommend using json2.js from https://github.com/douglascrockford/JSON-js
The reason why I recommend it is that some web browsers currently provide the same parsing functionality for JSON, and the above library is only used if the web browser doesn’t already have the ability to convert JSON content.

So, this way you can more safely convert the content, with:


var info = JSON.parse(req.responseText);

If the web browser doesn’t know how to do JSON.parse, the json2.js file nicely adds that capability for you.