Published on

Removing Comments from JSON String in JavaScript


When working with JSON, one of the frustrating things is that you can't have comments in it.

If you do have then, then it breaks.

Apparently, they had support for it in early versions of JSON specification but later it got removed just because the creator prefers so :(

However, it's such a useful and most wanted feature especially if you are maintaining configuration in JSON which is written by a human.

Here's how you can have a valid JSON with comments:


npm install strip-json-comments


import stripJsonComments from 'strip-json-comments';

const jsonString = `{
    // =====================  Editor 📝 ================================
    "editor.fontFamily": "Operator Mono, 'Fira Code'",
    "editor.fontLigatures": true,
    "editor.fontSize": 17, // default 17
    "editor.lineHeight": 24 // 24 Good Typography → 1.45 times of fontSize
/* Output 👇
editor.fontFamily: "Operator Mono, 'Fira Code'",
editor.fontLigatures: true,
editor.fontSize : 17,
editor.lineHeight : 24

Check out their strip-json-comments docs to learn more about how to use this package efficiently.

Moreover, this package does not have any dependencies so it should work on any environment like a browser or node.

And if you have a complicated use case, then json5 might be a good choice for you.

Happy stripping comments!