My application has a large array of objects, which I stringify and save them to the disk. Unfortunately, when the objects in the array are manipulated, and sometimes replac
I don't understand why the complexity of the current best answers is needed, to get all the keys recursively. Unless perfect performance is needed, it seems to me that we can just call JSON.stringify() twice, the first time to get all the keys, and the second time, to really do the job. That way, all the recursion complexity is handled by stringify, and we know that it knows its stuff, and how to handle each object type :
function JSONstringifyOrder( obj, space )
{
var allKeys = [];
JSON.stringify( obj, function( key, value ){ allKeys.push( key ); return value; } )
allKeys.sort();
return JSON.stringify( obj, allKeys, space );
}