I'm getting the following (str) back from Disqus, JSON expected:
?({"code": 0, "response": {"username": "FakeGrimlock", "about": "ME GIANT ROBOT DINOSAUR. WRITE CODE FOR STARTUP. EAT HUMANS THAT BORING OR STUPID. DRINK COFFEE AND BEER. ", "name": "FAKE GRIMLOCK", "url": "http://WWW.FAKEGRIMLOCK.COM", "profileUrl": "http://disqus.com/FakeGrimlock/", "emailHash": "07bb07626b48f05c093d70fb69ef8a76", "avatar": {"permalink": "http://disqus.com/api/users/avatars/FakeGrimlock.jpg", "cache": "http://mediacdn.disqus.com/uploads/users/437/9401/avatar92.jpg?1313888496"}, "isAnonymous": false, "id": "4379401"}});
so I fix it...
str='[' + str.substr(2, str.le开发者_如何学编程ngth-4) + ']'
which gives us this:
[{"code": 0, "response": {"username": "FakeGrimlock", "about": "ME GIANT ROBOT DINOSAUR. WRITE CODE FOR STARTUP. EAT HUMANS THAT BORING OR STUPID. DRINK COFFEE AND BEER. ", "name": "FAKE GRIMLOCK", "url": "http://WWW.FAKEGRIMLOCK.COM", "profileUrl": "http://disqus.com/FakeGrimlock/", "emailHash": "07bb07626b48f05c093d70fb69ef8a76", "avatar": {"permalink": "http://disqus.com/api/users/avatars/FakeGrimlock.jpg", "cache": "http://mediacdn.disqus.com/uploads/users/437/9401/avatar92.jpg?1313888496"}, "isAnonymous": false, "id": "4379401"}}]
...which passes at JSONLINT, and then try to get it into an object here...
var obj=JSON.parse(str);
console.log(obj) displays this:
[ { code: 0, response: { username: 'FakeGrimlock', about: 'ME GIANT ROBOT DINOSAUR. WRITE CODE FOR STARTUP. EAT HUMANS THAT BORING OR STUPID. DRINK COFFEE AND BEER. ', name: 'FAKE GRIMLOCK', url: 'http://WWW.FAKEGRIMLOCK.COM', profileUrl: 'http://disqus.com/FakeGrimlock/', emailHash: '07bb07626b48f05c093d70fb69ef8a76', avatar: [Object], isAnonymous: false, id: '4379401' } } ]
And then it fails here:
console.log(obj.response[0])// response is undefined.
Testing the obj output in JSONLINT shows an error, which I'm assuming is that the "" were removed by JSON.Parse.
Regardless, I'm not able to access the data.
Simple. Your JSON object is an array (the leading '['). Try this:
obj[0].response
Or just don't surround it with brackets to start with...
精彩评论