methods for removing json comments using javascript

Looking to remove JSON comments using JavaScript? I believe a regular expression would be the most efficient method.

{
    "field": { // comments
         "n": 1 /* multi-line ...
                                 comments */
    },
    "field2": " // comments in string , /* here */ "
}

This should be effective for the provided example.
Note: comments within strings should not be deleted.

Update: I understand that comments in JSON are not standard, but for simplicity, I want to include them and then remove them. Many tools can handle parsing JSON with comments.

Update 2: The example above is actually a string, I failed to mention that (apologies), and I see some responses assuming it is JavaScript code.

Update 3: I once again forgot to enclose key names in double quotes, the question has been updated.

Answer №1

While leaving comments in JSON may not be common practice, there are situations where it can be beneficial. I created a small nodejs package specifically for this purpose: json-easy-strip

Your JSON file can include any valid JavaScript comments:

{
    /*
     * Delicious section
     */
    "fruit": "Watermelon", // Yes, watermelons are delicious!
    "dessert": /* Yummy! */ "Cheesecake",
    // And lastly
    "drink": "Milkshake - /* strawberry */ or // chocolate!" // Mmm...
}

Here is how the comments can be stripped:

//
// Our JSON string
let jsonString = `{
    /*
     * Delicious section
     */
    "fruit": "Watermelon", // Yes, watermelons are delicious!
    "dessert": /* Yummy! */ "Cheesecake",
    // And lastly
    "drink": "Milkshake - /* strawberry */ or // chocolate!" // Mmm...
}`;

//
// One-liner comment remover
jsonString = jsonString.replace(/\\"|"(?:\\"|[^"])*"|(\/\/.*|\/\*[\s\S]*?\*\/)/g, (m, g) => g ? "" : m);

//
// Parse jsonString and display the result
console.log(JSON.parse(jsonString));

//
// Result
//  {
//    fruit: "Watermelon",
//    dessert: "Cheesecake",
//    drink: "Milkshake - /* strawberry */ or // chocolate!"
//  }

Answer №2

A quick and efficient method involves using JSON.stringify followed by JSON.parse to easily clean up the data.

Answer №3

Utilize the javascript parser to handle it:

a = {
    filed: { // comments
         n: 1 /* multi-line ...
                                 comments */
    },
    field2: " // comments in string , /* here */ "
}
a.toSource()
/*
({filed:{n:1}, field2:" // comments in string , /* here */ "})
*/

You have the option to achieve the same outcome with a string (based on the edited question) in a similar manner:

a =   'a = {\r\n  filed: { // comments  n: 1 \r\n/* multi-line ...  comments */\r\n},\r\n'
    + 'field2: " // comments in string , /* here */ "\r\n}'
eval(a).toSource().toString();

However, it appears that this method does not function with chrome. Oh, I overlooked, it is specifically for FF, my apologies (in Javascript version 3).

I discovered an alternative at https://gist.github.com/archan937/1961799 so the following will function in most other browsers as well.

function inspect(object) {
  switch (typeof(object)) {
  case "undefined":
    return "undefined";
  case "string":
    return "\"" + object.replace(/\n/g, "\\n").replace(/\"/g, "\\\"") + "\"";
  case "object":
    if (object == null) {
      return "null";
    }
    var a = [];
    if (object instanceof Array) {
      for (var i in object) {
        a.push(inspect(object[i]));
      };
      return "[" + a.join(", ") + "]";
    } else {
      for (var key in object) {
        if (object.hasOwnProperty(key)) {
          a.push(key + ": " + inspect(object[key]));
        }
      };
      return "{" + a.join(", ") + "}";
    }
  default:
    return object.toString();
  }
};

a = 'a = {\r\n  filed: { // comments  n: 1 \r\n/* multi-line ...  comments */\r\n},\r\n'
    + 'field2: " // comments in string , /* here */ "\r\n}'

alert(inspect(eval(a)));

Answer №4

If you're looking to eliminate comments, especially in JSON5 format, you should check out the decomment library available at this link.

This powerful tool can effectively remove comments from JSON5, JavaScript ES6, CSS, and even HTML with ease.

const decomment = require('decomment');

const exampleCode = "let x; // a comment";

decomment(exampleCode); //=> let x;

Answer №5

Here's my take on it: if you're considering keeping an invalid JSON file with comments for production purposes, that's your call. However, deploying such a file on your live website and then resorting to JavaScript workarounds to make it function properly isn't the best look. I suggest creating a clean JSON file for deployment and keeping the commented code for your eyes only. The end user doesn't need to see it, and unnecessary indenting spaces only add to the data transfer size.

If you're looking to remove those comments, here's one approach:

var invalidJSON = "{\n\"filed\": { // comments\n\"n\": 1 /* multi-line ...\ncomments */\n},\n\"field2\": \" // comments in string , /* here */ \"\n}";

eval("var result = " + invalidJSON);
var result = JSON.stringify(result);
alert(result); // The result should be a valid JSON object

Alternatively, you can treat it as JavaScript instead of JSON with a few modifications to the file:

// file.js
var data = {
    "filed": { // comments
         "n": 1 /* multi-line ...
                                 comments */
    },
    "field2": " // comments in string , /* here */ "
};

In your HTML page:

<script type="text/javascript" src="file.js"></script>

This will import the object to your page under the name data.

Answer №6

Many responses suggest using eval, but I caution against it. While it may appear harmless, using eval can introduce risks. Instead, I recommend avoiding eval, even for simple tasks like this.

Here is my modified version of Havenard's solution, which employs a similar yet safer approach.

var invalid_json = "{\n\"filed\": { // comments\n\"n\": 1 /* multi-line ...\ncomments */\n},\n\"field2\": \" // comments in string , /* here */ \"\n}";

var json = (new Function("return " + invalid_json))();
var x = JSON.stringify(json);
alert(x); // x should be valid JSON of that

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Trigger a function on q-select change using onChange event (Quasar Framework)

I'm trying to get the function to run when I change the selected value, but it's not working. How can I solve this issue? Below is the code I am using: <q-select v-model="single" :options="['def', 'abc', ...

Creating a nested datatable from a JSON array object response is a valuable skill to have in

My API response is in JSON format with nested arrays. I am trying to parse it into a nested datatable, but I can't seem to get it working. Can someone please point out where I went wrong? The JSON data contains passenger information and each passenger ...

Defining the signature of an unnamed function in TypeScript

Within my Express code, I have an anonymous function set up like this: app.use((err, req, res, next) => { // ... }); I am looking to specify the type of the function as ErrorRequestHandler (not the return type). One way to achieve this is by defining ...

Categorizing information within a Python document

My document contains data in a specific structure: CC ----------------------------------------------------------------------- CC CC hgfsdh kjhsdt kjshdk CC CC ----------------------------------------------------------------------- CC Release of 18 ...

Update the form action URL when a specific option is selected from the dropdown menu upon clicking the submit

I would like my form to redirect to a specific page on my website based on the selection made in the <select> tag. For instance, if '2checkout' is selected, it should go to gateways/2checkout/2checkout.php. Similarly, if 'Payza' i ...

What could be causing the drop-down values to fail to be saved?

I'm dealing with an address object that has nested objects for both permanent and postal addresses. Despite successfully saving the values of input boxes in a large form, I'm facing an issue with not being able to save the dropdown (select) value ...

Exploring the power of nested loops within an AJAX call in Angular

I have been attempting to iterate through a variable, search for IDs, and then make an ajax call to retrieve the detailed content of the different IDs. In the Success function, I am trying to loop through the received content and extract the emails. While ...

The Problem with AJAX Error Handling Customization

Upon loading my webpage using Code Igniter and PHP, the JSON encoded query is returned successfully with data. I have managed to handle the scenario where no records are found by encoding a response in JSON format. However, I am unsure of how to transmit t ...

The AJAX status is now 0, with a ready state of 4

Struggling to execute an AJAX call (using only JavaScript) to store a user in the database. The JavaScript file I am working with includes this code: var url = "interfata_db.php"; xmlhttp.onreadystatechange = function(){ alert('ready state &apos ...

Running a designated AJAX function from a variable by utilizing Applescript

Struggling to execute a JavaScript code within a page using Applescript. In the JavaScript, an AJAX function was defined like so: var myFunction = function () { // Here be the code... } I attempted this in Applescript: do JavaScript "document.myFunct ...

Script for collapsing or expanding is non-functional

Although I am a beginner in Javascript coding, I am eager to learn more about it. I stumbled upon some tutorials on creating collapse/expand <div> blocks. After testing the code on jsfiddle, I found that it works fine there. You can find the code he ...

Logging out of Laravel after sending a POST request

I'm developing a laravel application that heavily relies on POST requests. One common type of request in my app looks like this: var classElements = document.querySelectorAll("tr.ui-selected td.filename"); var csrf = $('input[name=_token]') ...

Managing a JSON dictionary to a text file: Tips and tricks

I am working with a sample.json file that contains code in the C language dataset, represented as a dictionary. { "0_0": "int curl_mvsprintf ( char * buffer , const char * format , va_list ap_save ) {\n int retcode ;\n retcode = ...

AngularJS: Issues with data retrieval in parallel in $http get requests within a $.each loop

Attempting to fetch data for multiple IDs is the goal: (Simplified version, aiming to clarify) Controller: var idList = [39,40,41]; $.each(idList, function(key, value){ var dataObject = { type: "test", id: value }; var getData = DataFactor ...

Storing data from an API response into the localStorage using Vue.js upon clicking

My objective is to save specific data in the browser's localStorage upon clicking a link. However, the output I receive is either undefined or completely empty. <li v-for="(category, index) in categories" :key="index"> ...

Encountered an unexpected character while parsing the GCP authentication file using Newtonsoft.Json

I'm attempting to establish a connection between my local C# program and GCP (Bigquery). I have obtained a credentials JSON file from GCP that appears like this: { "type": "service_account", "project_id": "projec ...

Converting and storing Canvas data as a blob, and then saving the blob as

There is a clickable icon on the page that triggers an action when clicked. Currently, the icon is set as an anchor tag. However, I want to change it to a div like all the other icons in my UI. But for some reason, the following code isn't working. W ...

Tips for keeping the scrollbar permanently at the bottom in JavaScript?

I am trying to implement a feature where a div always scrolls down automatically. scrollDown(){ var chat = this.conversation; this.conversation.scrollTop = chat.scrollHeight; } checkKeyPress(e){ if (e.key == "Enter") { this.scrollDown(); .. ...

Retrieve data from a JSON array using either JavaScript or PHP

Check out my code snippet: const newData = [{"new_id":"1","new_no":"1","total":"N.A"},{"new_id":"2","new_no":"3","total":"4"},{"new_id":"2","new_no":"4","total":"5"}]; Now, I need to extract specific details from this JSON data based on the 'new_no& ...

In Nodejs, the value of req.headers['authorization'] is not defined when using JWT (JSON Web Token)

Below is the implementation of JWT in Node.js: const express = require("express"); const jwt = require("jsonwebtoken"); const app = express(); app.use(express.json()); const user = [ { name: "Rohan", id: 1, }, { name: "Sophie", id ...