将Json响应保存到数组中的方法

时间:2011-06-25 12:46:46

标签: javascript jquery json

我希望将每个json响应保存在一个像我这样编写的数组中

$(document).ready(function () {
   var saveJson = [];
   var jsonResponse = getjsonResponse()
                      //something with $get function response json format 
   saveJson = saveToArray(jsonResponse.SearchResults);

   var saveToArray = function(array){
       $.each(array,function(i,data){
           saveJson.push(data);
       });
   };
});

但似乎是我的代码不起作用saveJson得到未定义我怎么能克服这个?我只想将json响应附加到一个数组对象。

我的样本回复看起来像

    "SearchResults":[
          {
             "TypeFlag":"W",
             "HashCode":"66093013",
             "ShortenKey":"http:///k",
             "Title":"Yahoo! \u003cspan class=\"search-result-highlight\"\u003eSearch\u003c/span\u003e - Web \u003cspan class=\"search-result-highlight\"\u003eSearch\u003c/span\u003e",
             "Description":"The \u003cb\u003esearch\u003c/b\u003e engine that helps you find exactly what you\u0027re looking for. Find the most relevant information, video, images, and answers from all across the Web.",
             "Url":"http://search.yahoo.com/",
             "LastUpdateOn":"6/21/2011 1:01:11 PM",
             "PageRank":1,
             "ThumbImageUrl":""
          },
         {
             "TypeFlag":"W",
             "HashCode":"48394089",
             "ShortenKey":"http:///5i",
             "Title":"Lijit | Advertising Services, Audience Analytics and Publisher ...",   
             "Description":"I’ve been using Lijit as my site \u003cb\u003esearch\u003c/b\u003e for several years and the understanding I get about my audience is critical to knowing what my readership is interested in and ...",
             "Url":"http://www.lijit.com/",
             "LastUpdateOn":"6/22/2011 11:31:41 PM",
             "PageRank":10,
             "ThumbImageUrl":""
      }
]

感谢

2 个答案:

答案 0 :(得分:2)

function(array){
    $.each(array,function(i,data){
        saveJson.push(data);
    });
};

返回 undefined 。虽然您将数据推送到saveJson,但是“saveJson = saveToArray(jsonResponse)”会将saveJson重新指定为 undefined

你可能有:

function(array){
    var ret = [];
    $.each(array,function(i,data){
        ret.push(data);
    });
    return ret;
};

答案 1 :(得分:0)

您的JSON不是数组,实际上您在“SearchResults”中有一个包含数组的对象,因此您必须将其传递而不是整个对象:

saveJson = saveToArray(jsonResponse.SeachResults); //change this line

(假设jsonResponse已定义)