Anon
Anon

Reputation: 59

Format JSON and save it using NodeJS

I have a couple of JSON files that I generated using a tool. The problem is, even thought this JSONs are valid, they don't have any indentation at all.

I already tried something like this:

fs.readdir(path, function (err, files) {
    if (err) {
        return console.log('Unable to scan directory: ' + err);
    } 
    files.forEach((file) => {
        const pathToFile =  `../jsonFiles/${file}`;
        fs.readFile(pathToFile, 'utf-8', (err, data) => {
            fs.writeFile(pathToFile, JSON.parse(JSON.stringify(data, null, 4)), (err) => {
                 if (err) {
                     console.log(err)
                }
            });

        });
    });
});

Upvotes: 1

Views: 79

Answers (1)

Niklas
Niklas

Reputation: 1948

Just use JSON.stringify(data, null, 4) instead of JSON.parse(JSON.stringify(...)) and also add utf8 to the options of fs.writeFile:

fs.readdir(path, function (err, files) {
    if (err) {
        return console.log('Unable to scan directory: ' + err);
    } 
    files.forEach((file) => {
        const pathToFile =  `../jsonFiles/${file}`;
        fs.readFile(pathToFile, 'utf-8', (err, data) => {
            fs.writeFile(pathToFile, JSON.stringify(data, null, 4), 'utf8', (err) => {
                 if (err) {
                     console.log(err)
                }
            });

        });
    });
});

Edit: I read your question again. I think you switched parse and stringify of the data, that you read as a string. I fixed it:

fs.readdir(path, function (err, files) {
    if (err) {
        return console.log('Unable to scan directory: ' + err);
    } 
    files.forEach((file) => {
        const pathToFile =  `../jsonFiles/${file}`;
        fs.readFile(pathToFile, 'utf-8', (err, data) => {
            fs.writeFile(pathToFile, JSON.stringify(JSON.parse(data), null, 4), 'utf8', (err) => {
                 if (err) {
                     console.log(err)
                }
            });

        });
    });
});

Upvotes: 3

Related Questions