-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
88 lines (65 loc) · 1.82 KB
/
index.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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
"use strict";
var json = {
/**
* Set JSON value by key
*
* @param object obj JSON object, passed by reference
* @param string path
* @return this
*/
set: function (obj, path, value) {
var part;
var parts = path.replace(/\[(.*?)\]/g, ".$1").split(".");
var last = parts.pop();
var isArray = false;
if (last == '') {
isArray = true;
}
else {
parts.push(last);
}
while(typeof (part = parts.shift()) != 'undefined') {
if (parts.length == 0) {
if (isArray) {
if (toString.call(obj[part]) != '[object Array]') obj[part] = [];
obj[part].push(value);
}
else {
obj[part] = value;
}
}
else {
if( typeof obj[part] != "object") obj[part] = {};
}
// update "pointer"
obj = obj[part];
}
return this;
},
/**
* Get JSON value by key
*
* @param object obj JSON object
* @param string path
* @return object
*/
get: function(obj, path) {
var part;
var parts = path.replace(/\[(.*?)\]/g, ".$1").split(".")
var pattern = new RegExp(/home\[(.*)\]/);
while (part = parts.shift()) {
var match = part.match(/(.*)\[(.*)\]/);
if (match !== null) {
obj = obj[match[1]]
if (typeof obj == 'undefined') return obj;
obj = obj[match[2]];
}
else {
if (typeof obj[part] == 'undefined') return obj[part];
obj = obj[part];
}
}
return obj;
}
};
module.exports = json;