summaryrefslogtreecommitdiff
path: root/share/server/util.js
diff options
context:
space:
mode:
authorJan Lehnardt <jan@apache.org>2009-07-24 16:07:52 +0000
committerJan Lehnardt <jan@apache.org>2009-07-24 16:07:52 +0000
commit7b400c260c7c93bb24ff0e13dc2575af8751f35a (patch)
tree2a771862ce31023ff2ff290d2a72a773944f9700 /share/server/util.js
parentb58eb73f281ebb9f741fc924afe52cc14f709a3d (diff)
speed up json encoding, patch by Brian Candler, closes COUCHDB-399
git-svn-id: https://svn.apache.org/repos/asf/couchdb/trunk@797548 13f79535-47bb-0310-9956-ffa450edef68
Diffstat (limited to 'share/server/util.js')
-rw-r--r--share/server/util.js29
1 files changed, 16 insertions, 13 deletions
diff --git a/share/server/util.js b/share/server/util.js
index 35a3a539..1f69bf16 100644
--- a/share/server/util.js
+++ b/share/server/util.js
@@ -10,16 +10,9 @@
// License for the specific language governing permissions and limitations under
// the License.
-function toJSON(val) {
- if (typeof(val) == "undefined") {
- throw "Cannot encode 'undefined' value as JSON";
- }
- var subs = {'\b': '\\b', '\t': '\\t', '\n': '\\n', '\f': '\\f',
+toJSON.subs = {'\b': '\\b', '\t': '\\t', '\n': '\\n', '\f': '\\f',
'\r': '\\r', '"' : '\\"', '\\': '\\\\'};
- if (typeof(val) == "xml") { // E4X support
- val = val.toXMLString();
- }
- return {
+toJSON.dispatcher = {
"Array": function(v) {
var buf = [];
for (var i = 0; i < v.length; i++) {
@@ -43,20 +36,20 @@ function toJSON(val) {
return isFinite(v) ? v.toString() : "null";
},
"Object": function(v) {
- if (v === null) return "null";
+ //if (v === null) return "null";
var buf = [];
for (var k in v) {
if (!v.hasOwnProperty(k) || typeof(k) !== "string" || v[k] === undefined) {
continue;
}
- buf.push(toJSON(k, val) + ": " + toJSON(v[k]));
+ buf.push(toJSON(k) + ": " + toJSON(v[k]));
}
return "{" + buf.join(",") + "}";
},
"String": function(v) {
if (/["\\\x00-\x1f]/.test(v)) {
v = v.replace(/([\x00-\x1f\\"])/g, function(a, b) {
- var c = subs[b];
+ var c = toJSON.subs[b];
if (c) return c;
c = b.charCodeAt();
return '\\u00' + Math.floor(c / 16).toString(16) + (c % 16).toString(16);
@@ -64,7 +57,17 @@ function toJSON(val) {
}
return '"' + v + '"';
}
- }[val != null ? val.constructor.name : "Object"](val);
+};
+
+function toJSON(val) {
+ if (typeof(val) == "undefined") {
+ throw "Cannot encode 'undefined' value as JSON";
+ }
+ if (typeof(val) == "xml") { // E4X support
+ val = val.toXMLString();
+ }
+ if (val === null) { return "null"; }
+ return (toJSON.dispatcher[val.constructor.name])(val);
}
function compileFunction(source) {