jQuery解析JSON

时间:2010-02-22 22:09:43

标签: jquery json

我正在尝试解析从SocialMention返回的JSON。

以下是JSON的示例:

{"title":"Social Mention","count":100,"items":[{"title":"RT @Jason_IIATMS: More Damon-isms that'll make you wanna puke: \"Let's hope the Chinese are right when they say this is the year of the tiger!\"","description":"","link":"http:\/\/twitter.com\/NYBD\/statuses\/9495530392","timestamp":1266876271,"image":null,"embed":null,"user":"NYBD","user_image":"http:\/\/a1.twimg.com\/profile_images\/60347208\/155135_logo_final_normal.jpg","user_link":"http:\/\/twitter.com\/NYBD","user_id":3265448,"source":"twitter","favicon":"http:\/\/twitter.com\/favicon.ico","type":"microblogs","domain":"twitter.com","id":"6111418866093918428"},

我正在使用jquery的.getJson,例如:

$.getJSON("Home/GetSocialMentionData", function (data) {
    $.each(data.items, function (i, item) {
        alert(i);
    });
});

我显然没有做正确的事情因为我从未到达alert(i)且经常收到JavaScript错误“Microsoft JScript运行时错误:'length'为null或不是对象”

我是JSON的新手,在谷歌搜索时似乎找不到任何东西。

所以我的问题是,我如何解析结果?任何有用的建议都会很棒。

5 个答案:

答案 0 :(得分:5)

从jQuery 1.4+开始,你JSON必须有效才能工作,我的意思是完全有效。您可以验证您的JSON using JSONLint here

根据您发布的内容,它无效...但似乎是一个片段,因此请输入您的完整结果,看看您是否有任何错误。

答案 1 :(得分:3)

而不是$ .getJSON,执行经典的AJAX调用并将类型指定为JSON:

$.ajax({
    type: "GET",
    url: "Home/GetSocialMentionData",
    dataType: "json",
    success: function (data) {
        // parsed json
    }
})

修改

如果问题仍然存在,我会推荐使用JSON parser并直接在您的成功函数中调用var obj = JSON.parse(data)。如果失败,你的json文本肯定有问题

答案 2 :(得分:1)

这可能没有做任何事情,但它真的有你的json字符串末尾的最后一个“,”吗?这可能会激怒getJSON方法......

编辑:进一步检查后,您的JSON无效。您可以在此处查看http://json.parser.online.fr/

编辑:好的,这个怎么样

$.getJSON("Home/GetSocialMentionData", function(data) {
    for (var itemIndex in data.items) {
        var item = data.items[itemIndex];
        alert(item);
    }
});

可能只是

$.getJSON("Home/GetSocialMentionData", function(data) {
    for (var itemIndex in data) {
        var item = data[itemIndex];
        alert(item);
    }
});

没有看到其余部分很难说,但尝试一下,看看你是否收到警报。

为了将来参考,您还可以使用JSON.stringify(string)方法来确定json字符串(或几乎所有对象)包含的内容。试一试:-)

答案 3 :(得分:1)

无需手动反序列化JSON。 $ .getJSON会在执行回调函数之前为您执行此操作。

我建议使用Firebug(或类似的浏览器内调试器)在$ .each()之前在回调中设置断点,并检查实际返回的内容。听起来像data.items不存在或者不是数组。

答案 4 :(得分:0)

我过去使用jQuery的AJAX函数http://api.jquery.com/jQuery.ajax/而不是getJSON来解决这些问题。