使用jQuery循环并获取JSON数组的键/值对
我正在寻找循环JSON数组并显示键和值。
I'm looking to loop through a JSON array and display the key and value.
它应该是以下帖子的简化版本,但我似乎没有正确的语法: jQuery'每个'循环使用JSON数组
It should be a simplified version of the following post, but I don't seem to have the syntax correct: jQuery 'each' loop with JSON array
我还看到帖子 使用jQuery获取JSON中键/值对的键名称? ,但它似乎也是一个简单活动的代码。
I also saw the post Get name of key in key/value pair in JSON using jQuery?, but it also seemed like lots of code for a simple activity.
这说明了我正在寻找的东西(但它不起作用):
This illustrates what I'm looking for (but it doesn't work):
var result = '{"FirstName":"John","LastName":"Doe","Email":"johndoe@johndoe.com","Phone":"123 dead drive"}';
$.each(result, function(k, v) {
//display the key and value pair
alert(k + ' is ' + v);
});
没有强制性的jQuery要求,但它是可用的。如果它减少了所需的代码,我也可以重构JSON。
There is no mandatory jQuery requirement, but it is available. I can also restructure the JSON if it cuts down the required code.
你有一个表示JSON序列化JavaScript对象的字符串。在能够遍历其属性之前,需要将其反序列化为JavaScript对象。否则你将循环遍历该字符串的每个字符。
You have a string representing a JSON serialized JavaScript object. You need to deserialize it back to a JavaScript object before being able to loop through its properties. Otherwise you will be looping through each individual character of this string.
var resultJSON = '{"FirstName":"John","LastName":"Doe","Email":"johndoe@johndoe.com","Phone":"123 dead drive"}';
var result = $.parseJSON(resultJSON);
$.each(result, function(k, v) {
//display the key and value pair
alert(k + ' is ' + v);
});
现场演示。