When using JSON.stringify(value, replacer), the output may vary between Chrome and Firefox

I'm encountering an issue when attempting to utilize JSON.stringify with the "replacer" function.

var scriptTag = document.createElement('script');
        scriptTag.type = 'text/javascript';
        scriptTag.src = 'https://wicked-good-xpath.googlecode.com/files/wgxpath.install.js';
        document.body.appendChild(scriptTag);


function censor(censor) {
  var i = 0;

  return function(key, value) {

console.log(i,typeof(censor),'=====',typeof(value), value);    
    if(i !== 0 && /*typeof(censor) === 'object' && typeof(value) == 'object' && */ censor == value) 
      return null; 
console.log(i,typeof(censor),'=====',typeof(value), value); 
    if(i >= 29) // seems to be a harded maximum of 30 serialized objects?
      return null;
console.log(i,typeof(censor),'=====',typeof(value), value); 
    ++i; // so we know we aren't using the original object anymore

    return value;  
  };
}

XPathResult = document.evaluate('**<SOME XPATH HERE>**', document, null, XPathResult.ANY_TYPE, null);
var actualNode = XPathResult.iterateNext();
                    var result = [];
                    while (actualNode) {
                        result.push(jQuery.makeArray(actualNode));
                        actualNode = XPathResult.iterateNext();
                    }
console.log(result);                
console.log("Result: ", JSON.stringify(result, censor(result)));

or pastebin

The challenge arises in DevTools and Firebug where the 'JSON.stringify(result, censor(result)));' output differs -

Chrome output:

console output of **30** objects

Result:  [[{"width":"","vAlign":"","scope":"col","rowSpan":1,"noWrap":false,"height":"","headers":"","colSpan":1,"chOff":"","ch":"","bgColor":"","axis":"","align":"","abbr":"","cellIndex":4,"spellcheck":true,"isContentEditable":false,"contentEditable":"inherit","children":{"length":0},"outerText":"PUBLICATION DATE","outerHTML":"<th scope=\"col\" class=\"sortDesc byPublicationDate\" style=\"cursor: pointer;\">PUBLICATION DATE</th>","innerText":"PUBLICATION DATE","innerHTML":"PUBLICATION DATE","accessKey":"","hidden":false,"webkitdropzone":null,"draggable":null,"tabIndex":null,"dir":null,"translate":null,"lang":null,"title":null,"id":null,"webkitShadowRoot":null,"webkitPseudo":null,"childElementCount":null,"nextElementSibling":null,"previousElementSibling":null,"lastElementChild":null,"firstElementChild":null,"dataset":null,"classList":null,"className":null,"scrollHeight":null,"scrollWidth":null,"scrollTop":null,"scrollLeft":null,"clientHeight":null,"clientWidth":null,"clientTop":null,"clientLeft":null,"offsetParent":null,"offsetHeight":null,"offsetWidth":null,"offsetTop":null,"offsetLeft":null,"style":null,"tagName":null,"parentElement":null,"textContent":null,"baseURI":null,"localName":null,"prefix":null,"namespaceURI":null,"ownerDocument":null,"attributes":null,"nextSibling":null,"previousSibling":null,"lastChild":null,"firstChild":null,"childNodes":null,"parentNode":null,"nodeType":null,"nodeValue":null,"nodeName":null,"jQuery17109208346924278885":null}]]

and FF output:

*console output of **3** objects

Result: 
[[{"jQuery171005647180282625541":13}]]*

Could someone clarify why there is a discrepancy between these browsers and suggest modifications to achieve consistency across them? By the way, 'result' remains consistent in both browsers.

P.S. I referred to that question for creating censor()

Answer №1

Implement a callback method that passes the reference of censor instead of its value, thus allowing for a simpler implementation:

var censor = "";
function executeCensor(key, value)
   {
    if(censor == value) 
      return null; 
    else
      return value;  
   }

JSON.stringify(output, censor);

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

Organize a collection of objects based on their individual keys

How can an array of objects be grouped based on keys using vanilla JavaScript, especially when dealing with a large number of records like 10000? Here is a sample object to illustrate: [ { company: "TATA", car: "TATA Indica", color: "Blue" }, { ...

What is the best way to prevent excessive rerenders when verifying if database information has been successfully retrieved?

Hey there, I'm encountering an issue where the if statement check in my code is causing a "too many rerenders" problem. I'm trying to create a delay between pulling data from the database and calculating the BMI. Any suggestions on how to resolve ...

Utilize a script to interact with CasperJS

When it comes to running my CasperJS script, I typically do so from the command line interface using this command: casperjs --ignore-ssl-errors=true --ssl-protocol=any scrape.js In order to fully automate the process, I am now looking into calling the sc ...

How can you convert all nodes of a nested JSON tree into class instances in Angular 2 using Typescript?

I have a Leaf class that I want to use to convert all nodes in a JSON response into instances of Leaf. The structure of the JSON response is as follows: JSON Response { "name":"animal", "state":false, "children":[ { "name" ...

The password generated refuses to be saved

I've encountered an issue with saving a hashed password. Previously, when I saved the password as it was, everything worked fine. However, after implementing bcrypt for encryption, the process no longer works. The JSON response no longer includes the ...

Attach a button and arrow to the cursor while it is hovering

Can anyone help me figure out how to make a button magnetize the content (arrow) along with it when hovered over by the cursor? I found an example of what I want on this website , but I am struggling to implement it in my own code. I've searched thro ...

Utilizing the principles of object orientation in Javascript to enhance event management

After attempting to modularize my JavaScript and make it object oriented, I found myself struggling when dealing with components that have multiple instances. This is an example of how my code currently looks: The HTML file structure is as follows: & ...

Associating Map with Scala attributes

Why use a JSON data structure? {"query":{"count":1,"created":"2014-04-28T07:33:09Z","lang":"en-US","results":{"rate":{"id":"USDCNY","Rate":"6.2489","Date":"4/28/2014","Time":"3:30am","Ask":"6.2494","Bid":"6.2484"}}}} The specific data of interest is: ...

Creating multiple versions of a website based on the user's location can be achieved by implementing geotargeting techniques

It may be a bit challenging to convey this idea clearly. I am interested in creating distinct home pages based on the source from which visitors arrive. For instance, if they come from FaceBook, I envision a tailored home page for FaceBook users. If they ...

Adding style tags dynamically to a component and then encapsulating the styles again (using Angular)

Currently, I am in the process of upgrading from AngularJS to Angular. Our app is currently a hybrid one being bundled up with webpack instead of just angular cli. Due to this setup, we have encountered issues where our css or scss files are not correctly ...

Adjust the slide count accordingly when navigating to a particular item within the Bootstrap 3 Carousel

I made adjustments to the standard Bootstrap 3 Carousel so that it can navigate to a specific slide when the URL matches #. Although this feature is working, I am facing an issue with my pager-text not updating correctly when jumping to a specific slide. T ...

When clicking initially, the default input value in an Angular 2 form does not get set

I am currently learning angular2 as a beginner programmer. My goal is to create a form where, upon clicking on an employee, an editable form will appear with the employee's current data. However, I have encountered an issue where clicking on a user f ...

I'm looking to generate a semicircle progress bar using jQuery, any suggestions on how

Hi there! I'm looking to create a unique half circle design similar to the one showcased in this fiddle. Additionally, I want the progress bar to be displayed in a vibrant green color. I've recently started learning about Jquery and would apprec ...

I am currently facing an issue with validating forms in JavaScript Document Object Model (DOM)

Whenever I click on a field and move to another one, the span tag turns red. Then, after pressing the submit button, an alert message pops up. However, if I turn the span red, fill in the field, and press the submit button, it shows success even if other f ...

Tips for preventing unstyled content flash when updating CSS files dynamically

The following jQuery function is used to replace CSS files: function UpdateTheme(theme) { var links = $("link"); var _t = theme; $.each(links, function (i, link) { var _h = $(link).attr('href'); _updatedHr ...

What is the method for adjusting the size of text while rendering on a canvas?

When it comes to scaling text with CSS transform scale, for instance: transform: scale(2, 4); fontSize: 20px // Is including fontSize necessary? I also have the task of displaying the same text on a canvas element. function draw() { const ctx = document ...

Tips for incorporating external functions into Vue Component data synchronization:

As someone new to JavaScript, I am trying to incorporate external functions into Vue component data bindings, but I am encountering issues. helper.js function groupArrayOfObjects(list, key) { return blah blah } function parseDate(d) { ret ...

What sets $(document).on apart from ($ document).on in CoffeeScript?

One of my buddies is incorporating ($ document).on into his CoffeeScript script. I'm curious to know if this differs from the typical $(document).on and, if it does, how so? ...

Comparison between modules and standalone components

It has come to my attention that there is a growing trend in Angular 17 to move away from using modules, opting instead for standalone components. This approach makes Angular more similar to Vuejs or React, where the concept of modules is not as prominent. ...

Securely Saving JWT Tokens from Auth0 Login in Node.js Express

As a novice in the world of Auth0, I am currently working on integrating it into my regular express web application. My main goal is to secure and validate users before they are able to access certain endpoints. From what I have gathered, this can be achie ...