开发者

iterate through json string

Need a little help here. I'm new to Coldfusion and I use CF6. I used QueryToArrayOfStructures and jsonencode from CFLib.org to convert my query to array of structs ,and then 开发者_如何转开发serialize it to json format.

The result I get looks like this: [{"lastname":"aaa"},{"lastname":"bbb"},{"lastname":"ccc"}]

What I need to do is get the values of the lastname, ie aaa, bbb, and ccc. I tried to use $.each but could not get it working:

$.each(data, function(){
  $.each(this, function(key,value){
    resultHtml+='<div class="result">';
    resultHtml+='<h2><a href="#"> Last name: '+ value +'</a></h2>'; 
    resultHtml+='</div>';
  });
});

$('div#results').html(resultHtml);

What I get in the results div would be each of the characters in the data. For example, I would get:

[
{
"
l
a
s
t
n
a
m
e

... and so on. Thanks.


It seems you might first need to parse the JSON string with parseJSON. After you have the JSON parsed. you should be able to do $.each() over it.

Here you go


What is can see is that the first loop through the array of objects and you dont have to do a second loop.

what you can do is as below

var data =  [{"lastname":"aaa"},{"lastname":"bbb"},{"lastname":"ccc"}];
var resultHtml = '';

$.each(data, function(key,value){       
    resultHtml+='<div class="result">';
    resultHtml+='<h2><a href="#"> Last name: '+ value.lastname +'</a></h2>';
    resultHtml+='</div>';
});

$('div#results').html(resultHtml);

I hope this helps you!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜