How to Remove Comments from JSON Array in Javascript?

Nov 21, 2022 . Admin



Hello friends,

This simple article demonstrates how to remove comments from JSON array in javascript. you can understand the concept of removing comments. This article will give you an example of how to remove comments from JSON array in javascript. I will explain to remove comments from the JSON array with an example.

To remove comments from the JSON array you can use replace() and JSON.parse, we have to see how to remove comments from a JSON array with an example.

So, let's see bellow solution:

Example:
index.html
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>How to Remove Comments from JSON Array in Javascript?</title>
</head>
<body>
<script type="text/javascript">

    //create JsonString
    let jsonString = `{
        /*
         * Sweet section
         */
        "fruit": "Watermelon", // Yes, watermelons are sweet!
        "dessert": /* Yummy! */ "Cheesecake"
    }`;
    
    // One-liner comment stripper
    jsonString = jsonString.replace(/\\"|"(?:\\"|[^"])*"|(\/\/.*|\/\*[\s\S]*?\*\/)/g, (m, g) => g ? "" :m);

    // Parse jsonString and print the result
    console.log(JSON.parse(jsonString));
    
</script>
</body>
</html>
Check The Console For Output:
{fruit: 'Watermelon', dessert: 'Cheesecake'}

I hope it will help you...

#Javascript