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

标签 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":""
      }
]

谢谢

最佳答案

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

返回未定义。虽然您将数据推送到 saveJson,但您的“saveJson = saveToArray(jsonResponse)”将 saveJson 重新分配为 undefined

你可能有:

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

关于javascript - 将 Json 响应保存到数组的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6477802/

相关文章:

jquery - AJAX 调用,仅在加载帖子时添加加载器

javascript - 无法在 Internet Explorer 中显示这个简单的 .hide() 代码

ios - 从服务中获取数据 Objective c

json - 如何执行 PUT 操作来更新 Jmeter 中的 API?

javascript - ajax成功访问类函数

php - javascript翻译,在php中编码,在javascript中解码

javascript - 带有 JQuery 验证的表单生成器

json - 如何将 JSON 对象转换为 TypeScript 类?

javascript - 这是什么迭代?

javascript - 使用 '+' 而不是 '%20' 来解码 URI