如何获得JSON密钥和价值?

时间:2011-08-16 05:09:15

标签: jquery asp.net json

我编写了以下代码来从webservice获取JSON结果。

function SaveUploadedDataInDB(fileName) {
            $.ajax({
                type: "POST",
                url: "SaveData.asmx/SaveFileData",
                data: "{'FileName':'" + fileName + "'}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    var result = jQuery.parseJSON(response.d);
                    //I would like to print KEY and VALUE here.. for example
                    console.log(key+ ':' + value)
                    //Addess : D-14 and so on..
                   }
            });
        }

以下是来自webservice的回复enter image description here

请帮我打印Key及其值

3 个答案:

答案 0 :(得分:94)

看起来你回来了一个阵列。如果它总是由一个元素组成,那么你可以这样做(是的,它与Tomalak的答案几乎相同):

$.each(result[0], function(key, value){
    console.log(key, value);
});

如果您可能有多个元素并且想要对它们进行迭代,则可以嵌套$.each()

$.each(result, function(key, value){
    $.each(value, function(key, value){
        console.log(key, value);
    });
});

答案 1 :(得分:11)

$.each(result, function(key, value) {
  console.log(key+ ':' + value);
});

答案 2 :(得分:10)

首先,我看到你正在使用明确的$.parseJSON()。如果那是因为您在服务器端手动序列化JSON,请不要。 ASP.NET will automatically JSON-serialize your method's return value和jQuery会自动为你反序列化。

要遍历数组中的第一项,请使用以下代码:

var firstItem = response.d[0];

for(key in firstItem) {
  console.log(key + ':' + firstItem[key]);
}

如果有多个项目(很难从该屏幕截图中看出来),那么您可以遍历response.d,然后在该外部循环中使用此代码。