我想从数组中创建多个JSON文件。
数组:
[{
"Reference": "Registration",
"langkey": "REG_LBL",
"English": "Company Registration",
"Japanese": "会社登録"
}, {
"Reference": "Registration",
"langkey": "INFO_LBL",
"English": "Company Information",
"Japanese": "会社情報"
}]
我需要从上面的数组中创建两个名为英语和日语的JSON文件(它将是动态的)。
所需输出
English.json
{
'INFO_LBL' : 'Company Information',
'REG_LBL':'Company Registration'
}
Japanese.json
{
'INFO_LBL' : '会社情報',
'REG_LBL':'会社情報'
}
代码
for (var i = 0; i < data.length; i++) {
var obj = data[i];
for (var key in obj) {
if (key !=='Reference' && key !== 'langkey' ) {
//{'REG_LBL':'Company Registration'}
objects[obj['langkey']] = obj[key];
fs.writeFileSync('lang/' + langkey + '.json', JSON.stringify(objects, null, 2), { encoding: 'utf8' }, function (err) {
if (err)
{ throw err; }
console.log("completed")
});
}
}
}
我很乐意创建两个JSON文件,但内容会被另一个文件覆盖。请帮忙解决这个问题?
答案 0 :(得分:2)
var finalObject = {};//create new object
data.forEach(v => {
var langkey = v.langkey;
Object.keys(v).forEach(val => {
if (val != 'langkey' && val != 'Reference') {
if (finalObject[val]) {//find if language object is already created.If already created insert in it else create new
let data = {};
data[langkey] = v[val]
finalObject[val] = Object.assign(finalObject[val], data)
} else {
finalObject[val] = {};
finalObject[val][langkey] = v[val];
}
}
})
})
Object.keys(finalObject).forEach(key => {
fs.writeFileSync(path.join(__dirname, `/lang/${key}.json`), JSON.stringify(finalObject[key], null, 2), (err) => {
if (err)
{ throw err; }
console.log('completed');
});
})
答案 1 :(得分:1)
您的阵列中有2个项目,还有2种语言,那么您需要拥有4个json文件吗? INFO_LBL(英语&amp; japanesh)2,REG_LBL(英语&amp; japanesh)2?或者你只需要2个json文件用于第二个项目INFO_LBL(English&amp; japanesh)?
更新:贝娄是你的解决方案
for (var i = 0; i < data.length; i++) {
var obj = data[i];
for (var key in obj) {
if (key !== 'Reference' && key !== 'langkey') {
var newObject = {};
var path = 'lang/' + key + '.json';
if (fs.existsSync(path)) {
var newObject = JSON.parse(fs.readFileSync(path, 'utf8'));
}
newObject[obj.langkey] = obj[key];
fs.writeFileSync(path, JSON.stringify(newObject, null, 2), { encoding: 'utf8' });
}
}
}
答案 2 :(得分:0)
这个有效。我使用window ['newVariable'];
为每个创建了单独的对象var myArray =
[{
"Reference": "Registration",
"langkey": "REG_LBL",
"English": "Company Registration",
"Japanese": "会社登録"
}, {
"Reference": "Registration",
"langkey": "INFO_LBL",
"English": "Company Information",
"Japanese": "会社情報"
}];
for(i=0; i<myArray.length; i++){
window['myJSON' + i] = myArray[i];
}
console.log(myJSON0, myJSON1);
这是我得到的,两个独立的对象
现在你所要做的就是将字符串化为JSON。
答案 3 :(得分:0)
如果您的数据被覆盖,那将是因为writeFileSync。您应该使用appendFileSync或writeFileSync的标志