操作JSON数据
Posted .x->y=z
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了操作JSON数据相关的知识,希望对你有一定的参考价值。
操作标准JSON数据,递归实现如下:
String.prototype.startWith = function(compareStr) {
return this.indexOf(compareStr) == 0;
}
// 生成以rootNode为根节点的树
function generateSubtree(rootNode, childrenJson) {
for(var idx = 0; idx < childrenJson.length; ++idx) {
var child = childrenJson[idx];
// 子节点
var childNode = {
"name": child.name,
"desc": child.desc,
"dsp=": child.name.startWith("节点-1") ? "Y" : "N",
"children": []
};
// 如果有孩子则生成其子树
if (child.children != null && child.children != \'[]\') {
generateSubtree(childNode, child.children);
}
// childNode子树作为rootNode的孩子
rootNode.children.push(childNode);
}
}
实例如下:
1 <html> 2 <head> 3 <meta charset="utf-8" /> 4 <script src="http://code.jquery.com/jquery-2.1.1.min.js"></script> 5 <script type="text/javascript"> 6 var stdJsonData = { 7 "name": "根结点", 8 "desc": "根结点描述", 9 "children": [ 10 { 11 "name": "节点-1", 12 "desc": "节点-1-描述", 13 "children": [ 14 { 15 "name": "节点-1-1", 16 "desc": "节点-1-1描述", 17 "children": [ 18 { 19 "name": "节点-1-1-1", 20 "desc": "节点-1-1-1描述", 21 "children": [ 22 { 23 "name": "节点-1-1-1-1", 24 "desc": "节点-1-1-1-1描述", 25 "children": [ 26 { 27 "name": "节点-1-1-1-1-1", 28 "desc": "节点-1-1-1-1-1描述" 29 }, 30 { 31 "name": "节点-1-1-1-1-2", 32 "desc": "节点-1-1-1-1-2描述" 33 }, 34 { 35 "name": "节点-1-1-1-1-3", 36 "desc": "节点-1-1-1-1-3描述", 37 "children": [ 38 { 39 "name": "节点-1-1-1-1-3-1", 40 "desc": "节点-1-1-1-1-3-1描述" 41 }, 42 { 43 "name": "节点-1-1-1-1-3-2", 44 "desc": "节点-1-1-1-1-3-2描述" 45 }, 46 { 47 "name": "节点-1-1-1-1-3-3", 48 "desc": "节点-1-1-1-1-3-3描述" 49 } 50 ] 51 } 52 ] 53 }, 54 { 55 "name": "节点-1-1-1-2", 56 "desc": "节点-1-1-1-2描述", 57 "children": [ 58 { 59 "name": "节点-1-1-1-2-1", 60 "desc": "节点-1-1-1-2-1描述" 61 }, 62 { 63 "name": "节点-1-1-1-2-2", 64 "desc": "节点-1-1-1-2-2描述" 65 }, 66 { 67 "name": "节点-1-1-1-2-3", 68 "desc": "节点-1-1-1-2-3描述" 69 } 70 ] 71 }, 72 { 73 "name": "节点-1-1-1-3", 74 "desc": "节点-1-1-1-3描述" 75 }, 76 { 77 "name": "节点-1-1-1-4", 78 "desc": "节点-1-1-1-4描述" 79 } 80 ] 81 }, 82 { 83 "name": "节点-1-1-2", 84 "desc": "节点-1-1-2描述" 85 }, 86 { 87 "name": "节点-1-1-3", 88 "desc": "节点-1-1-3描述", 89 "children": [ 90 { 91 "name": "节点-1-1-3-1", 92 "desc": "节点-1-1-3-1描述" 93 }, 94 { 95 "name": "节点-1-1-3-2", 96 "desc": "节点-1-1-3-2描述" 97 }, 98 { 99 "name": "节点-1-1-3-3", 100 "desc": "节点-1-1-3-3描述" 101 } 102 ] 103 } 104 ] 105 }, 106 { 107 "name": "节点-1-2", 108 "desc": "节点-1-2描述" 109 }, 110 { 111 "name": "节点-1-3", 112 "desc": "节点-1-3描述" 113 } 114 ] 115 }, 116 { 117 "name": "节点-2", 118 "desc": "节点-2-描述", 119 "children": [ 120 { 121 "name": "节点-2-1", 122 "desc": "节点-2-1描述", 123 "children": [ 124 { 125 "name": "节点-2-1-1", 126 "desc": "节点-2-1-1描述", 127 "children": [ 128 { 129 "name": "节点-2-1-1-1", 130 "desc": "节点-2-1-1-1描述", 131 "children": [ 132 { 133 "name": "节点-2-1-1-1-1", 134 "desc"VSCode 如何操作用户自定义代码片段(快捷键)