[英]JS Loop through a json Object
i am trying to iterate a json object (in javascript) but it doesn't seem to work correctly... it's very confusing for me to write a recursiv function, so maybe one of the experts here could help me :) 我正在尝试迭代一个json对象(在javascript中),但是它似乎无法正常工作...对我来说,编写一个递归函数非常令人困惑,所以也许这里的一位专家可以帮助我:)
The json Object: json对象:
{
"Node": [
{
"Name": {
"#text": "Folder"
}
},
{
"Name": {
"#text": "Folder 2"
}
},
{
"Name": {
"#text": "Folder 3"
},
"Nodes": {
"Node": {
"Name": {
"#text": "Folder 3.1"
},
"Nodes": {
"Node": [
{
"Name": {
"#text": "Folder 3.1.1"
},
"Nodes": {
"Node": {
"Name": {
"#text": "Folder 3.1.1.1"
}
}
}
},
{
"Name": {
"#text": "Test 2"
}
}
]
}
}
}
},
{
"Name": {
"#text": "Folder 4"
}
}
]
}
My try to solve the problem 我试图解决问题
function newFolder(_data) {
for (var i = 0; i < _data.length; i++) {
if (_data[i].Nodes) {
Ti.API.info("Sub: "); //+ _data[i].Nodes.Node.length );
return newFolder(_data[i].Nodes.Node);
} else {
Ti.API.info("Main: " + _data[i].Name["#text"]);
}
Ti.API.info("Main: " + _data[i].Name["#text"]);
}
}
The problem is, that the functions does not run through each element, like i want to. 问题是,函数没有像我想要的那样贯穿每个元素。
i've read something about jQuery each but i'm not very familar with that. 我每个人都读过一些有关jQuery的东西,但是我对此并不十分熟悉。 plus i am using Titanium and i don't know exactly if i can use jquery. 再加上我正在使用Titanium,我不知道我是否可以使用jquery。
it would be soo awesome if someone can help me out of this :) 如果有人可以帮助我,那太好了:)
I think that your JSON
is very complex as there is no need. 我认为您的JSON
非常复杂,因为没有必要。 If you have an object like this: 如果您有这样的对象:
var data = {
"nodes": [
{ "name": "Folder 1" },
{ "name": "Folder 2" },
{ "name": "Folder 3" },
{
"name": "Folder 4",
"nodes": [
{ "name": "Folder 4.1" },
{
"name": "Folder 4.2",
"nodes": [
{ "name": "Folder 4.2.1" },
{ "name": "Folder 4.2.2" },
{ "name": "Folder 4.2.3" }
]
},
{ "name": "Folder 4.3" }
]
},
{ "name": "Folder 5" }
]
};
You can iterate over it by a recursive function : 您可以通过递归函数对其进行迭代 :
function iterateNodes(data) {
for (var i = 0, l = data.nodes.length; i < l; i++) {
var node = data.nodes[i];
console.log(node.name);
if (node.nodes) {
arguments.callee(node);
}
}
}
iterateNodes(data);
Check the FIDDLE Demo . 检查FIDDLE演示 。
JSON is multi array , we can use data[a][b]... to get it. JSON是多数组,我们可以使用data [a] [b] ...来获取它。
function xmlhttprequest(url) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
var data = JSON.parse(xhr.responseText);
console.log(data);
for(var a in data){
document.write(a+':<br>');
for(var b in data[a]){
document.write(' '+b+':<br>');
for(var c in data[a][b]){
document.write(' '+c+"="+data[a][b][c]+'<br>');
}
}
document.write('<br>');
}
}else{
alert(url+'\n错误');
}
}
}
xhr.open('GET', url, false);
xhr.send();
};
xmlhttprequest('https://api.shuax.com/tools/getchrome/json');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.