i looking way write json object file, maintaining same formatting orignal. have managed write content using writefilesync(path,data) , json.stringify() struggling figure out how customise formatting. options json.stringify accepts seem format number of spaces.
is there way tho using json.stringify generate following formatting
{ "key1" :{"key": "value1","key": "value2"}, "key2" :{"key": "value1","key": "value2"} }
instead of 1 generated default
{ "key1": { "key": "value1", "key": "value2" }, "key2": { "key": "value1", "key": "value2" }, }
unfortunately not, can use space argument define spacing of objects fall in on tree. you're proposing require custom formatting using regular expressions format strings after stringify it.
below you'll find sample code you're looking however. can append of these single command json.stringify(myjson, null, ' ').replace(/: \{\n\s+/g, ': {').replace(/",\n\s+/g, ', ').replace(/"\n\s+\}/g, '}');
, see did, broke down step step.
const myjson = { "key1":{"key": "value1","key2": "value2"}, "key2":{"key": "value1","key2": "value2"} } let mystring = json.stringify(myjson, null, ' ').replace(/: {/g, `${' '.repeat(5)}: \{`); //set key spacing mystring = mystring.replace(/: \{\n\s+/g, ': {'); //bring child bracket on same line mystring = mystring.replace(/",\n\s+/g, ', '); //bring other objects array mystring = mystring.replace(/"\n\s+\}/g, '}'); //pull closing bracket on same line const mycompactstring = json.stringify(myjson, null, ' ').replace(/: {/g, `${' '.repeat(5)}: \{`).replace(/: \{\n\s+/g, ': {').replace(/",\n\s+/g, ', ').replace(/"\n\s+\}/g, '}'); //done @ once console.log(`mystring: ${mystring}`); console.log(`mycompactstring: ${mycompactstring}`);
Comments
Post a Comment