Ok I think I am having a bad moment. Usually I can iterate over JSON without issue.
Here is a Sample String
{
"service 1": {
"admin": {},
"list": [
"1"
],
"info": [
{
"id": "1",
"details": "Failed",
"curr-status": "Warning",
"curr-status-class": "warning"
}
],
"status": [
{}
]
},
"service 2": {
"admin": {},
"list": [
"1"
],
"info": [
{
"id": "1",
"details": "Failed",
"curr-status": "Warning",
"curr-status-class": "warning"
}
],
"status": [
{}
]
}
}
What I am trying to do is be able to do an $.each() on every service then make a pretty list out of it, and eventually sort based on etc..
My last failed attempt at iterating through it is:
$('.refreshAllb').click(function()
{
$.post('services.json', {"x":"blank"}, function(data)
{
$('body').html('');
$.each(data, function(i)
{
$.each(data[i], function(x, z)
{
$('body').append(x.z+"<br>");
});
});
}, "json");
});
I have looped over various concepts of running each() with an each() to being a lone each. All I keep returning is object object or undefined. So I know I am in the ballpark but I am not hitting the nail on the head.. ideas?
-
right now I am still getting virtually nothing returned. I am getting "o, undefined, undefined, undefined". All I wanna do is print "Service 1", "Service 2" I'd be happy with just that at this point..chris– chris2011年10月03日 22:17:52 +00:00Commented Oct 3, 2011 at 22:17
1 Answer 1
$('.refreshAllb').click(function() {
$.post('services.json', {"x":"blank"}, function(data) {
$('body').empty();
$.each(data, function(serviceName) {
$.each(this, function(key) {
$('body').append(serviceName + "." + key + "=" + this + "<br/>");
});
});
}, "json");
});
answered Oct 3, 2011 at 21:56
Eric
98.1k54 gold badges257 silver badges389 bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
chris
nice, alright. Now I am getting somewhere. Is there a specific reason as to why my initial approach wasn't working? I usually handle it in similar fashions as per my original post, but this one got me beat. It'd be nice to understand more where the fail aspect of what i was doing comes into play.
Eric
@chris: You need to remind yourself of the behaviour of jQuery.each. The first argument passed to the callback is the key, and the second is the value, not the other way around. Note that
this is the same as the second parameter, so you shouldn't need the second parameter in most cases.lang-js