如何将数组树转换为Json树
How to convert an array tree to Json tree?
我有一个数组,保持数据在树结构,但我想将此数据转换为json。这是我的数据的例子:
[Object]
0: Object
children: Array[1]
0: Object
children: Array[1]
0: Object
children: Array[10]
0: Object
children: Array[6]
value: Object
1: Object
2: Object
3: Object
4: Object
5: Object
6: Object
7: Object
8: Object
9: Object
value: Object
Id: "00145E5BB2641EE284F811A7907757A3"
Parent: "00145E5BB2641EE284F811A7907737A3"
Ref: undefined
Text: "Functional Areas"
Type: "TWB"
现在我要将这些数据数组转换为Json。我尝试JSON.stringify(myArray);但是格式不正确。它破坏了树的所有结构。什么好主意吗?
这是给出上述结果的代码。
function transformToStruct(xmlData, callback) {
var data = xmlData.item;
var roots=[];
var children = {};
var arry=createStructure(data);
// find the top level nodes and hash the children based on parent
for (var i = 0, len = arry.length; i < len; ++i) {
var item = arry[i],
p = item.Parent,
target = [];
if(p == rootId) {
target = roots;
}
else {
target = (children[p] || (children[p] = []));
}
target.push({ value: item });
}
// function to recursively build the tree
var findChildren = function(parent) {
if (children[parent.value.Id]) {
parent.children = children[parent.value.Id];
for (var i = 0, len = parent.children.length; i < len; ++i) {
findChildren(parent.children[i]);
}
}
};
// enumerate through to handle the case where there are multiple roots
for (var i = 0, len = roots.length; i < len; ++i) {
findChildren(roots[i]);
}
// var returnV = JSON.stringify(roots);
// callback(returnV);
callback(roots)
}
function createStructure(data) {
var arry = [];
$.each(data, function(i, val) {
var parent = val["ParentId"]["#text"];
var id = val["NodeId"]["#text"];
var text = val["NodeText"]["#text"];
var level = val["NodeLevel"]["#text"];
var ref = val["RefObject"]["#text"];
var type = (val["NodeType"]["#text"]).substring(0,3);
if(level == "01")
rootId = parent;
var item = {"Id": id, "Text": text, "Parent": parent, "Type" : type, "Ref" : ref};
arry[i] = item;
// arry.push(item);
});
console.log(arry)
return arry;
}
JSON可以将原生JavaScript对象编码("stringify")为字符串符号。它可以从该符号反向创建该对象的另一个实例。
示例:var myArray = new Array("a", "b", "c");
var jsonNotation = JSON.stringify(myArray);
console.log(jsonNotation);
将:
[
"a",
"b",
"c"
]
上面的代码
[Object]
0: Object
children: Array[1]
不是JavaScript
相关文章:
- 转换 JSON 日期,不考虑时区
- 转换 JSON 文件
- 使用正则表达式转换 JSON 密钥值
- 如何通过javascript转换JSON中的DC2type:数组和DC2type中的JSON
- 转换json中的整数值
- 转换JSON架构格式
- 转换JSON "/日期(1404860400000)"到javascript日期
- 在js中转换json数组
- 检索原始日期值转换JSON.stringify
- Java脚本转换json数据
- 用JS转换JSON字符串
- 转换JSON数组的对象,从两个属性值创建新的属性
- 在AngularJs中转换JSON对象
- 需要转换JSON格式
- 转换JSON中的字符串
- 如何转换json数组的JS
- jQuery UI自动完成与预转换json url
- 使用递归转换json数据
- 如何在jquery中转换json格式的数组
- 如何转换json没有& quot;