代码之家  ›  专栏  ›  技术社区  ›  Jack Marchetti

jQuery解析JSON

  •  2
  • Jack Marchetti  · 技术社区  · 15 年前

    下面是一个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"},
    

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

    alert(i) 并且经常出现JavaScript错误“Microsoft JScript运行时错误:'length'为null或不是对象”

    我对JSON完全陌生,在谷歌上搜索时,我似乎找不到任何东西。

    5 回复  |  直到 15 年前
        1
  •  5
  •   Nick Craver    15 年前

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

        2
  •  3
  •   Juraj Blahunka    15 年前

    代替$.getJSON,执行经典AJAX调用并将类型指定为JSON:

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

    编辑

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

        3
  •  1
  •   T. Stone    15 年前

    编辑:进一步检查后,您的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);
        }
    });
    

    没有看到它的其余部分很难说,但试试看,看看你是否得到了一个警报。

        4
  •  1
  •   Dave Ward    15 年前

    无需手动反序列化JSON。$。在执行回调函数之前,getJSON会为您这样做。

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

        5
  •  0
  •   James    15 年前

    我过去使用AJAX函数解决了这些问题 http://api.jquery.com/jQuery.ajax/