JSON.stringify custom formatting

I am looking for a way to write a JSON object to a file, but maintaining the same formatting with the orignal. I have managed to write the content using writeFileSync(path,data) and JSON.stringify() but struggling to figure out how to customise the formatting. The options JSON.stringify accepts seem to format only the number of spaces.

Is there any way tho using JSON.stringify to generate the following formatting

{
  "key1"           :{"key": "value1","key": "value2"},
  "key2"           :{"key": "value1","key": "value2"}
}

instead of the one generated by default

{
  "key1": 
   {
     "key": "value1",
     "key": "value2"
   },
  "key2": 
   {
     "key": "value1",
     "key": "value2"
   },
}

Unfortunately not, you can use the space argument to define the spacing of the objects as they fall in on the tree. What you're proposing would require custom formatting using something like regular expressions to format the strings after you stringify it.

Below you'll find some sample code to do what you're looking to do however. You can append all of these into a single command like JSON.stringify(myJSON, null, ' ').replace(/: {ns+/g, ': {').replace(/",ns+/g, ', ').replace(/"ns+}/g, '}'); , however so you could see what I did, I broke it down step by step.

const myJSON = {
  "key1":{"key": "value1","key2": "value2"},
  "key2":{"key": "value1","key2": "value2"}
}

let myString = JSON.stringify(myJSON, null, ' ').replace(/: {/g, `${' '.repeat(5)}: {`); //Set the key spacing
myString = myString.replace(/: {ns+/g, ': {'); //Bring the child bracket on the same line
myString = myString.replace(/",ns+/g, ', '); //Bring all the other objects for that array up
myString = myString.replace(/"ns+}/g, '}'); //Pull the closing bracket on the same line

const myCompactString = JSON.stringify(myJSON, null, ' ').replace(/: {/g, `${' '.repeat(5)}: {`).replace(/: {ns+/g, ': {').replace(/",ns+/g, ', ').replace(/"ns+}/g, '}'); //Done all at once

console.log(`myString: ${myString}`);
console.log(`myCompactString: ${myCompactString}`);
链接地址: http://www.djcxy.com/p/48214.html

上一篇: 使用JavaScript打印JSON?

下一篇: JSON.stringify自定义格式