AnonymousOct 29, 2023
Here's a Node.js script that create a JSON file from an array:
import fs from 'fs'
const dateObjects = [];
let newArray = ["apple", "banana", "cherry", "rice", "shake"]
newArray.forEach((i) => {
const dateObject = {
name: i
};
dateObjects.push(dateObject);
});
const jsonData = JSON.stringify(dateObjects, null, 2);
fs.writeFile('output.json', jsonData, (err) => {
if (err) {
console.error('Error writing JSON file:', err);
} else {
console.log('JSON file has been created successfully!');
}
});
After running this script, you will find a output.json
file in the same directory containing the generated JSON data.
output.json
:
[
{
"name": "apple"
},
{
"name": "banana"
},
{
"name": "cherry"
},
{
"name": "rice"
},
{
"name": "shake"
}
]