jSON Javascript解析节点中的问题

时间:2011-10-12 23:32:13

标签: json parsing node.js disqus

我从Disqus,JSON预期得到以下(str):

?({“code”:0,“response”:{“username”:“FakeGrimlock”,“about”:“ME GIANT ROBOT DINOSAUR。用于启动的写代码。吃贪吃或愚蠢的人。喝咖啡和BEER。“,”name“:”FAKE GRIMLOCK“,”url“:”http://WWW.FAKEGRIMLOCK.COM“,”profileUrl“:”http://disqus.com/FakeGrimlock/“,”emailHash“:”07bb07626b48f05c093d70fb69ef8a76“,”avatar“:{ “永久链接”:“http://disqus.com/api/users/avatars/FakeGrimlock.jpg”,“缓存”:“http://mediacdn.disqus.com/uploads/users/437/9401/avatar92.jpg?1313888496”},“isAnonymous”:false,“id”:“4379401”}});

所以我解决了......

str='[' + str.substr(2, str.length-4) + ']'

给了我们这个:

[{“code”:0,“response”:{“username”:“FakeGrimlock”,“about”:“我是巨型机器人恐龙。启动时写的代码。吃贪吃或愚蠢的人。喝咖啡和啤酒。“,”name“:”FAKE GRIMLOCK“,”url“:”http://WWW.FAKEGRIMLOCK.COM“,”profileUrl“:”http://disqus.com/FakeGrimlock/“,”emailHash“:”07bb07626b48f05c093d70fb69ef8a76“,”avatar“:{”永久链接“:”http://disqus.com/api/users/avatars/FakeGrimlock.jpg“,”缓存“:”http://mediacdn.disqus.com/uploads/users/437/9401/avatar92.jpg?1313888496“},”isAnonymous“:false,”id“:”4379401“}}]

...传递给JSONLINT,然后尝试将其放入对象中......

var obj=JSON.parse(str);

console.log(obj)显示:

[{code:0,     响应:      {username:'FakeGrimlock',        关于:'我巨大的机器人恐龙。 WRITE代码启动。吃婊子或愚蠢的人。饮料咖啡和啤酒。 ”,        名称:'FAKE GRIMLOCK',        网址:'http://WWW.FAKEGRIMLOCK.COM',        profileUrl:'http://disqus.com/FakeGrimlock/',        emailHash:'07bb07626b48f05c093d70fb69ef8a76',        头像:[对象],        isAnonymous:false,        id:'4379401'}}]

然后它在这里失败了:

console.log(obj.response[0])// response is undefined. 

在JSONLINT中测试obj输出会显示一个错误,我假设JSON.Parse删除了“”。

无论如何,我无法访问数据。

1 个答案:

答案 0 :(得分:1)

简单。您的JSON对象是一个数组(前导'[')。试试这个:

obj[0].response

或者只是不要用括号括起来开始......