angular.js/src/JSON.js

105 lines
2.5 KiB
JavaScript
Raw Normal View History

2010-01-09 23:02:43 +00:00
array = [].constructor;
2010-01-06 00:36:58 +00:00
2010-01-12 01:32:33 +00:00
function toJson(obj, pretty){
2010-01-06 00:36:58 +00:00
var buf = [];
2010-01-23 23:54:58 +00:00
toJsonArray(buf, obj, pretty ? "\n " : null, _([]));
2010-01-06 00:36:58 +00:00
return buf.join('');
};
2010-01-12 01:32:33 +00:00
function toPrettyJson(obj) {
2010-01-09 23:02:43 +00:00
return toJson(obj, true);
2010-01-06 00:36:58 +00:00
};
2010-01-12 01:32:33 +00:00
function fromJson(json) {
2010-01-06 00:36:58 +00:00
try {
2010-01-09 23:02:43 +00:00
var parser = new Parser(json, true);
2010-01-06 00:36:58 +00:00
var expression = parser.primary();
parser.assertAllConsumed();
return expression();
} catch (e) {
2010-01-12 00:15:12 +00:00
error("fromJson error: ", json, e);
2010-01-06 00:36:58 +00:00
throw e;
}
};
2010-01-12 01:32:33 +00:00
angular['toJson'] = toJson;
angular['fromJson'] = fromJson;
2010-01-06 00:36:58 +00:00
2010-01-23 23:54:58 +00:00
function toJsonArray(buf, obj, pretty, stack){
if (typeof obj == "object") {
if (stack.include(obj)) {
buf.push("RECURSION");
return;
}
stack.push(obj);
}
2010-01-06 00:36:58 +00:00
var type = typeof obj;
if (obj === null) {
buf.push("null");
} else if (type === 'function') {
return;
} else if (type === 'boolean') {
buf.push('' + obj);
} else if (type === 'number') {
if (isNaN(obj)) {
buf.push('null');
} else {
buf.push('' + obj);
}
} else if (type === 'string') {
return buf.push(angular['String']['quoteUnicode'](obj));
2010-01-06 00:36:58 +00:00
} else if (type === 'object') {
if (obj instanceof Array) {
buf.push("[");
var len = obj.length;
var sep = false;
for(var i=0; i<len; i++) {
var item = obj[i];
if (sep) buf.push(",");
if (typeof item == 'function' || typeof item == 'undefined') {
buf.push("null");
} else {
2010-01-23 23:54:58 +00:00
toJsonArray(buf, item, pretty, stack);
2010-01-06 00:36:58 +00:00
}
sep = true;
}
buf.push("]");
} else if (obj instanceof Date) {
buf.push(angular['String']['quoteUnicode'](angular['Date']['toString'](obj)));
2010-01-06 00:36:58 +00:00
} else {
buf.push("{");
if (pretty) buf.push(pretty);
var comma = false;
var childPretty = pretty ? pretty + " " : false;
var keys = [];
for(var k in obj) {
if (k.indexOf('$$') === 0)
continue;
keys.push(k);
}
keys.sort();
for ( var keyIndex = 0; keyIndex < keys.length; keyIndex++) {
var key = keys[keyIndex];
try {
var value = obj[key];
if (typeof value != 'function') {
if (comma) {
buf.push(",");
if (pretty) buf.push(pretty);
}
buf.push(angular['String']['quote'](key));
2010-01-06 00:36:58 +00:00
buf.push(":");
2010-01-23 23:54:58 +00:00
toJsonArray(buf, value, childPretty, stack);
2010-01-06 00:36:58 +00:00
comma = true;
}
} catch (e) {
}
}
buf.push("}");
}
}
2010-01-23 23:54:58 +00:00
if (typeof obj == "object") {
stack.pop();
}
2010-01-06 00:36:58 +00:00
};