我正在寻找一种将 JSON 对象写入文件的方法,但保持与原始格式相同的格式。 我已经设法使用 writeFileSync(path,data) 和 JSON.stringify() 编写内容,但很难弄清楚如何自定义格式。 JSON.stringify 接受的选项似乎只格式化空格数。
有没有办法使用 JSON.stringify 生成以下格式
{
"key1" :{"key": "value1","key": "value2"},
"key2" :{"key": "value1","key": "value2"}
}
而不是默认生成的
{
"key1":
{
"key": "value1",
"key": "value2"
},
"key2":
{
"key": "value1",
"key": "value2"
},
}
最佳答案
不幸的是,您可以使用space argument定义对象落在树上时的间距。您建议的内容需要使用正则表达式之类的自定义格式来在字符串化后格式化字符串。
下面您将找到一些示例代码来完成您想要做的事情。您可以将所有这些附加到单个命令中,例如 JSON.stringify(myJSON, null, ' ').replace(/: \{\n\s+/g, ': {').replace(/",\n\s+/g, ', ').replace(/"\n\s+\}/g, '}');
,但是为了让您可以看到我做了什么,我一步一步地分解了它。
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(/: \{\n\s+/g, ': {'); //Bring the child bracket on the same line
myString = myString.replace(/",\n\s+/g, ', '); //Bring all the other objects for that array up
myString = myString.replace(/"\n\s+\}/g, '}'); //Pull the closing bracket on the 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 all at once
console.log(`myString: ${myString}`);
console.log(`myCompactString: ${myCompactString}`);
关于javascript - JSON.stringify 自定义格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38832629/