forked from DavidDurman/FlexiJsonEditor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
jquery.jsoneditor.js
220 lines (174 loc) · 7.37 KB
/
jquery.jsoneditor.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
// Simple yet flexible JSON editor plugin.
// Turns any element into a stylable interactive JSON editor.
// Copyright (c) 2011 David Durman
// Licensed under the MIT license (http://www.opensource.org/licenses/mit-license.php).
// Dependencies:
// * jQuery
// * JSON (use json2 library for browsers that do not support JSON natively)
// Example:
// var myjson = { any: { json: { value: 1 } } };
// var opt = { change: function() { /* called on every change */ } };
// /* opt.propertyElement = '<textarea>'; */ // element of the property field, <input> is default
// /* opt.valueElement = '<textarea>'; */ // element of the value field, <input> is default
// $('#mydiv').jsonEditor(myjson, opt);
(function( $ ) {
$.fn.jsonEditor = function(json, options) {
options = options || {};
// Make sure functions or other non-JSON data types are stripped down.
json = parse(stringify(json));
var K = function() {},
onchange = options.change || K;
return this.each(function() {
JSONEditor($(this), json, onchange, options.propertyElement, options.valueElement);
});
};
function JSONEditor(target, json, onchange, propertyElement, valueElement) {
var opt = {
target: target,
onchange: onchange,
original: json,
propertyElement: propertyElement,
valueElement: valueElement
};
construct(opt, json, opt.target);
$('.property, .value', opt.target).live('blur focus', function() {
$(this).toggleClass('editing');
});
}
function isObject(o) { return Object.prototype.toString.call(o) == '[object Object]'; }
function isArray(o) { return Object.prototype.toString.call(o) == '[object Array]'; }
function isBoolean(o) { return Object.prototype.toString.call(o) == '[object Boolean]'; }
function isNumber(o) { return Object.prototype.toString.call(o) == '[object Number]'; }
function isString(o) { return Object.prototype.toString.call(o) == '[object String]'; }
var types = 'object array boolean number string null';
// Feeds object `o` with `value` at `path`. If value argument is omitted,
// object at `path` will be deleted from `o`.
// Example:
// feed({}, 'foo.bar.baz', 10); // returns { foo: { bar: { baz: 10 } } }
function feed(o, path, value) {
var del = arguments.length == 2;
if (path.indexOf('.') > -1) {
var diver = o,
i = 0,
parts = path.split('.');
for (var len = parts.length; i < len - 1; i++) {
diver = diver[parts[i]];
}
if (del) delete diver[parts[len - 1]];
else diver[parts[len - 1]] = value;
} else {
if (del) delete o[path];
else o[path] = value;
}
return o;
}
// Get a property by path from object o if it exists. If not, return defaultValue.
// Example:
// def({ foo: { bar: 5 } }, 'foo.bar', 100); // returns 5
// def({ foo: { bar: 5 } }, 'foo.baz', 100); // returns 100
function def(o, path, defaultValue) {
path = path.split('.');
var i = 0;
while (i < path.length) {
if ((o = o[path[i++]]) == undefined) return defaultValue;
}
return o;
}
function error(reason) { if (window.console) { console.error(reason); } }
function parse(str) {
var res;
try { res = JSON.parse(str); }
catch (e) { res = null; error('JSON parse failed.'); }
return res;
}
function stringify(obj) {
var res;
try { res = JSON.stringify(obj); }
catch (e) { res = 'null'; error('JSON stringify failed.'); }
return res;
}
function addExpander(item) {
if (item.children('.expander').length == 0) {
var expander = $('<span>', { 'class': 'expander' });
expander.bind('click', function() {
var item = $(this).parent();
item.toggleClass('expanded');
});
item.prepend(expander);
}
}
function construct(opt, json, root, path) {
path = path || '';
root.children('.item').remove();
for (var key in json) {
if (!json.hasOwnProperty(key)) continue;
var item = $('<div>', { 'class': 'item', 'data-path': path }),
property = $(opt.propertyElement || '<input>', { 'class': 'property' }),
value = $(opt.valueElement || '<input>', { 'class': 'value' });
if (isObject(json[key]) || isArray(json[key])) {
addExpander(item);
}
item.append(property).append(value);
root.append(item);
property.val(key).attr('title', key);
var val = stringify(json[key]);
value.val(val).attr('title', val);
assignType(item, json[key]);
property.change(propertyChanged(opt));
value.change(valueChanged(opt));
if (isObject(json[key]) || isArray(json[key])) {
construct(opt, json[key], item, (path ? path + '.' : '') + key);
}
}
}
function updateParents(el, opt) {
$(el).parentsUntil(opt.target).each(function() {
var path = $(this).data('path');
path = (path ? path + '.' : path) + $(this).children('.property').val();
var val = stringify(def(opt.original, path, null));
$(this).children('.value').val(val).attr('title', val);
});
}
function propertyChanged(opt) {
return function() {
var path = $(this).parent().data('path'),
val = parse($(this).next().val()),
newKey = $(this).val(),
oldKey = $(this).attr('title');
$(this).attr('title', newKey);
feed(opt.original, (path ? path + '.' : '') + oldKey);
if (newKey) feed(opt.original, (path ? path + '.' : '') + newKey, val);
updateParents(this, opt);
if (!newKey) $(this).parent().remove();
opt.onchange();
};
}
function valueChanged(opt) {
return function() {
var key = $(this).prev().val(),
val = parse($(this).val() || 'null'),
item = $(this).parent(),
path = item.data('path');
feed(opt.original, (path ? path + '.' : '') + key, val);
if ((isObject(val) || isArray(val)) && !$.isEmptyObject(val)) {
construct(opt, val, item, (path ? path + '.' : '') + key);
addExpander(item);
} else {
item.find('.expander, .item').remove();
}
assignType(item, val);
updateParents(this, opt);
opt.onchange();
};
}
function assignType(item, val) {
var className = 'null';
if (isObject(val)) className = 'object';
else if (isArray(val)) className = 'array';
else if (isBoolean(val)) className = 'boolean';
else if (isString(val)) className = 'string';
else if (isNumber(val)) className = 'number';
item.removeClass(types);
item.addClass(className);
}
})( jQuery );