diff --git a/jstests/core/shelltypes.js b/jstests/core/shelltypes.js index 3f109269b39..e2dc1e1bdf9 100644 --- a/jstests/core/shelltypes.js +++ b/jstests/core/shelltypes.js @@ -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')); + diff --git a/src/mongo/shell/types.js b/src/mongo/shell/types.js index b9a8c6b5474..4a1eaf8bde4 100644 --- a/src/mongo/shell/types.js +++ b/src/mongo/shell/types.js @@ -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 + "}";