0
0
mirror of https://github.com/mongodb/mongo.git synced 2024-12-01 01:21:03 +01:00

SERVER-13707 simplify tojsonObject

This commit is contained in:
Benety Goh 2014-05-01 16:05:39 -04:00
parent 6a3d6d0aff
commit 68c2f37993
2 changed files with 35 additions and 13 deletions

View File

@ -51,3 +51,28 @@ b = NumberInt(a.toNumber());
printjson(a);
assert.eq(tojson(a), tojson(b), "int");
// tojsonObject
// Empty object
assert.eq('{\n\t\n}', tojsonObject({}));
assert.eq('{ }', tojsonObject({}, '', true));
assert.eq('{\n\t\t\t\n\t\t}', tojsonObject({}, '\t\t'));
// Single field
assert.eq('{\n\t"a" : 1\n}', tojsonObject({a: 1}));
assert.eq('{ "a" : 1 }', tojsonObject({a: 1}, '', true));
assert.eq('{\n\t\t\t"a" : 1\n\t\t}', tojsonObject({a: 1}, '\t\t'));
// Multiple fields
assert.eq('{\n\t"a" : 1,\n\t"b" : 2\n}', tojsonObject({a: 1, b: 2}));
assert.eq('{ "a" : 1, "b" : 2 }', tojsonObject({a: 1, b: 2}, '', true));
assert.eq('{\n\t\t\t"a" : 1,\n\t\t\t"b" : 2\n\t\t}', tojsonObject({a: 1, b: 2}, '\t\t'));
// Nested fields
assert.eq('{\n\t"a" : 1,\n\t"b" : {\n\t\t"bb" : 2,\n\t\t"cc" : 3\n\t}\n}',
tojsonObject({a: 1, b: {bb: 2, cc: 3}}));
assert.eq('{ "a" : 1, "b" : { "bb" : 2, "cc" : 3 } }',
tojsonObject({a: 1, b: {bb: 2, cc: 3}}, '', true));
assert.eq('{\n\t\t\t"a" : 1,\n\t\t\t"b" : {\n\t\t\t\t"bb" : 2,\n\t\t\t\t"cc" : 3\n\t\t\t}\n\t\t}',
tojsonObject({a: 1, b: {bb: 2, cc: 3}}, '\t\t'));

View File

@ -612,16 +612,10 @@ tojsonObject = function(x, indent, nolint){
// push one level of indent
indent += tabSpace;
var total = 0;
for (var k in x) total++;
if (total == 0) {
s += indent + lineEnding;
}
var keys = x;
if (typeof(x._simpleKeys) == "function")
keys = x._simpleKeys();
var num = 1;
var fieldStrings = [];
for (var k in keys){
var val = x[k];
@ -631,14 +625,17 @@ tojsonObject = function(x, indent, nolint){
if (typeof DBCollection != 'undefined' && val == DBCollection.prototype)
continue;
s += indent + "\"" + k + "\" : " + tojson(val, indent, nolint);
if (num != total) {
s += ",";
num++;
}
s += lineEnding;
fieldStrings.push(indent + "\"" + k + "\" : " + tojson(val, indent, nolint));
}
if (fieldStrings.length > 0) {
s += fieldStrings.join("," + lineEnding);
}
else {
s += indent;
}
s += lineEnding;
// pop one level of indent
indent = indent.substring(1);
return s + indent + "}";