-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjson_expand.js
48 lines (48 loc) · 2.06 KB
/
json_expand.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
function jsonExpand(json) {
if (typeof json === "string") {
json = JSON.parse(json)
}
function expandDOM(object) {
var result;
var ul = document.createElement("ul");
if (Array.isArray(object)) {
result = document.createElement("span");
result.setAttribute("class", "a");
object.forEach(function (value, index) { //引数が配列のとき
var li = document.createElement("li");
var wrap = document.createElement("span");
var a = document.createElement("span");
wrap.setAttribute("class", "w");
a.setAttribute("class", "i");
wrap.appendChild(expandDOM(value));
a.appendChild(document.createTextNode(index));
li.appendChild(a);
li.appendChild(document.createTextNode(":"));
li.appendChild(wrap);
ul.appendChild(li);
});
result.appendChild(ul);
} else if (object instanceof Object) { //引数が配列ではないがオブジェクトのとき
result = document.createElement("span");
result.setAttribute("class", "o");
Object.keys(object).forEach(function (key) {
var li = document.createElement("li");
var wrap = document.createElement("span");
var a = document.createElement("span");
wrap.setAttribute("class", "w");
a.setAttribute("class", "k");
wrap.appendChild(expandDOM(object[key]));
a.appendChild(document.createTextNode(key));
li.appendChild(a);
li.appendChild(document.createTextNode(":"));
li.appendChild(wrap);
ul.appendChild(li);
});
result.appendChild(ul);
} else {
result = document.createTextNode(object);
}
return result;
}
return expandDOM(json); //DOM element を返す
}