jQuery 如何获取 JSON 键和值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7073837/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get JSON Key and Value?
提问by imdadhusen
I have written following code to get JSON result from webservice.
我编写了以下代码来从 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..
}
});
}
Here is response from webservice:
这是来自 webservice 的响应:
Please help me to print Key and it's Value
请帮我打印密钥及其值
回答by no.good.at.coding
It looks like you're getting back an array. If it's always going to consist of just one element, you could do this (yes, it's pretty much the same thing as Tomalak's answer):
看起来你正在取回一个数组。如果它总是只包含一个元素,你可以这样做(是的,这与 Tomalak 的答案几乎相同):
$.each(result[0], function(key, value){
console.log(key, value);
});
If you might have more than one element and you'd like to iterate over them all, you could nest $.each()
:
如果您可能有多个元素,并且想遍历所有元素,则可以嵌套$.each()
:
$.each(result, function(key, value){
$.each(value, function(key, value){
console.log(key, value);
});
});
回答by Tomalak
$.each(result, function(key, value) {
console.log(key+ ':' + value);
});
回答by Dave Ward
First, I see you're using an explicit $.parseJSON()
. If that's because you're manually serializing JSON on the server-side, don't. ASP.NET will automatically JSON-serialize your method's return valueand jQuery will automatically deserialize it for you too.
首先,我看到您正在使用显式$.parseJSON()
. 如果那是因为您在服务器端手动序列化 JSON,请不要这样做。ASP.NET 会自动对你的方法的返回值进行 JSON 序列化,jQuery 也会自动为你反序列化它。
To iterate through the first item in the array you've got there, use code like this:
要遍历数组中的第一项,请使用如下代码:
var firstItem = response.d[0];
for(key in firstItem) {
console.log(key + ':' + firstItem[key]);
}
If there's more than one item (it's hard to tell from that screenshot), then you can loop over response.d
and then use this code inside that outer loop.
如果有多个项目(很难从屏幕截图中看出),那么您可以循环response.d
,然后在外循环中使用此代码。