我需要合并两个JSON文件,并且需要保留其中一个文件中的字符串:
"weeks": "weeks\u00a0days"
在合并后,\u00a0
总是会变成空格:"weeks": "weeks days"
。
我希望它仍然保持为:"weeks": "weeks\u00a0days"
一些代码:
//merge.js
const fs = require('fs');
const test1 = fs.readFileSync('./test1.json', 'utf8');
const test2 = fs.readFileSync('./test2.json', 'utf8');
const merge = (obj1, obj2) =>
JSON.stringify({ ...JSON.parse(obj1), ...JSON.parse(obj2) }, null, 4);
const saveFile = (fileName, obj1, obj2) => {
fs.writeFile(`${__dirname}/${fileName}`, merge(obj1, obj2), err => {
if (err) throw err;
console.log(`The file ${fileName} has been saved!`);
});
};
saveFile('testFinal.json', test1, test2);
test1.json
{
"link": {
"about": "About",
"version": "version"
},
"items": {
"siteId": "Site ID",
"siteName": "Site name",
"siteType": "Site type",
"weeks": "weeks\u00a0days"
}
}
test2.json
{
"features": {
"activateFeatures": "Activate features",
"confirmation": "Confirmation",
"hardware": "Hardware",
"existingHardware": "Existing hardware",
"emailLicense": "Email license",
"downloadLicense": "Select quantity"
}
}
please help
const abc = require('./abc.json')
而不使用readFileSync()
呢?这样可以避免JSON.parse()
的调用以及由额外解析所引起的一切麻烦。 - William Chongmerge
,而是JSON.stringify
中的一个普遍缺陷,请参见 https://dev59.com/F1wZ5IYBdhLWcg3wROiO,https://dev59.com/N2ct5IYBdhLWcg3wL6ui#27252001。 - georg