I wanted to stringify an object on the first level without including a third-party library / too much code.
In case you look for the same, here is a quick one-liner to do so:
var json = JSON.stringify(obj, function (k, v) { return k && v && typeof v !== "number" ? (Array.isArray(v) ? "[object Array]" : "" + v) : v; });
The top level object will have no key, so it's always simply returned, however anything that is not a "number" on the next level will be casted to a string incl. a special case for arrays, otherwise those would be exposed further more.
If you don't like this special array case, please use my old solution, that I improved, too:
var json = JSON.stringify(obj, function (k, v) { return k && v && typeof v !== "number" ? "" + v : v; }); // will expose arrays as strings.
Passing an array instead of an object in the top level will work nonetheless in both solutions.
EXAMPLES:
var obj = {
keyA: "test",
keyB: undefined,
keyC: 42,
keyD: [12, "test123", undefined]
}
obj.keyD.push(obj);
obj.keyE = obj;
var arr = [12, "test123", undefined];
arr.push(arr);
var f = function (k, v) { return k && v && typeof v !== "number" ? (Array.isArray(v) ? "[object Array]" : "" + v) : v; };
var f2 = function (k, v) { return k && v && typeof v !== "number" ? "" + v : v; };
console.log("object:", JSON.stringify(obj, f));
console.log("array:", JSON.stringify(arr, f));
console.log("");
console.log("with array string cast, so the array gets exposed:");
console.log("object:", JSON.stringify(obj, f2));
console.log("array:", JSON.stringify(arr, f2));
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…