Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
242 views
in Technique[技术] by (71.8m points)

javascript - 使用jQuery循环并获取JSON数组的键/值对(Loop and get key/value pair for JSON array using jQuery)

I'm looking to loop through a JSON array and display the key and value.(我想循环一个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'each'循环与JSON数组) I also saw the post Get name of key in key/value pair in JSON using jQuery?(我还看到了使用jQuery在JSON中获取键/值对中键的名称?) , 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":"[email protected]","Phone":"123 dead drive"}'; $.each(result, function(k, v) { //display the key and value pair alert(k + ' is ' + v); }); There is no mandatory jQuery requirement, but it is available.(没有强制性的jQuery要求,但它是可用的。) I can also restructure the JSON if it cuts down the required code.(如果它减少了所需的代码,我也可以重构JSON。)   ask by JStark translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You have a string representing a JSON serialized JavaScript object.(您有一个表示JSON序列化JavaScript对象的字符串。)

You need to deserialize it back to a JavaScript object before being able to loop through its properties.(在能够遍历其属性之前,需要将其反序列化为JavaScript对象。) Otherwise you will be looping through each individual character of this string.(否则,您将循环遍历此字符串的每个单独字符。) var resultJSON = '{"FirstName":"John","LastName":"Doe","Email":"[email protected]","Phone":"123 dead drive"}'; var result = $.parseJSON(resultJSON); $.each(result, function(k, v) { //display the key and value pair alert(k + ' is ' + v); }); Live demo .(现场演示 。)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...