Access the name of a JSON value holder
I have the following JSON data:
{
"pages": {
"22989": {
"title": "Paris",
"links": [{
"ns": 0,
"title": "11th arrondissement of Paris"
}]
}
}
}
How do I access the string "22989", inside "pages"? (I wan开发者_JAVA百科t the name of the variable, not it's value.)
var object = {"pages":{"22989":{"title":"Paris","links":[{"ns":0,"title":"11th arrondissement of Paris"}]}}}
for(key in object.pages) {
alert(key); // "22989"
}
You're going to have some trouble with this one because you use an integer as an index. You might want to add some characters to it so that you can access it as pages[0]. Otherwise you can use dogbert's suggestion for using a for loop (and breaking at the first one).
Parse the json to create an object, then it is same as this :
how to fetch array keys with jQuery?
Have you tried this?
$.each(myJsonObj, function(key,val){
// do something with key and val
});
Try this.
var json = '{"pages": {"22989": {"title": "Paris","links": [{"ns": 0,"title": "11th arrondissement of Paris"}]}}}';
var items = $.parseJSON(json);
$.each(items.pages,function(key, val){
alert(key);
});
精彩评论