1

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

        });
    });
});

1 Answer 1

3

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

        });
    });
});
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for replying. In my case, this only adds a ton of '\' characters into the json
@Anon I have edited my answer as well. Please have a look. I think I found the real issue in context.
Thank you! Btw: You can use JSON.stringify(JSON.parse(data), null, '\t') to use tab to intend instead of four spaces.
Oh yes, that would be great. I really ignored the fact that I received the data as a string. Thanks for taking your time.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.