Gopesh
Gopesh

Reputation: 3950

Dynamic creation of Json files from array

I want to create multiple JSON files from an array.

Array :

 [{
    "Reference": "Registration",
    "langkey": "REG_LBL",
    "English": "Company Registration",
    "Japanese": "会社登録"
}, {
    "Reference": "Registration",
    "langkey": "INFO_LBL",
    "English": "Company Information",
    "Japanese": "会社情報"
}]

I need to create two JSON files name English and Japanese(it will be dynamic) from above array.

Desired Output

English.json

{
'INFO_LBL' : 'Company Information',
'REG_LBL':'Company Registration'
}

Japanese.json

{
'INFO_LBL' : '会社情報',
'REG_LBL':'会社情報'
}

Code

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")

            });

        }
    }
}

I am ale to create two JSON files but the content is overwritten by another.Please help to resolve this?

Upvotes: 0

Views: 259

Answers (4)

sandeep rajbhandari
sandeep rajbhandari

Reputation: 1296

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');
    });
})

Upvotes: 2

Fetrarij
Fetrarij

Reputation: 7326

You have 2 items in your array, and 2 languages both so do you need to have 4 json files? 2 for INFO_LBL (English & japanesh) and 2 for REG_LBL(English & japanesh) ? or do you just need 2 json files for the second item INFO_LBL (English & japanesh) ?

update: bellow is your solution

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' });
        }
    }
}

Upvotes: 1

Sachin Nayak
Sachin Nayak

Reputation: 1051

If your data is getting overwritten, it would be because of the writeFileSync. You should be using appendFileSync or the a flag for writeFileSync

Upvotes: 0

Abana Clara
Abana Clara

Reputation: 4650

This one works. I created separate objects for each using 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);

Here's what I got, two separate objects

enter image description here

Now all you have to do is stringify to JSON.

Upvotes: 0

Related Questions