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

Develop a JavaScript function to declare variables

I am currently attempting to develop a small memory game where the time is multiplied by the number of moves made by the player. Upon completion of all pairs, a JavaScript function is executed: function finish() { stopCount(); var cnt1 = $("#cou ...

Menus that mimic the style of Google Translate's select options

I'm looking to design an HTML select menu using CSS in a similar fashion to Google Translate's style on Google Translate. I've searched for tutorials online, but they all involve jQuery. Is there a way to achieve something similar using only ...

What are the steps to retrieve all memcached information using node.js?

One of my main objectives is to have the user session data expire when they close their browser. However, I am facing a challenge because my Server depends on memcached to function correctly. Therefore, I need to find a way to specifically delete the use ...

Determine if the user has clicked on the Save or Cancel button within the print dialog box

Hello everyone, Can anyone help me figure out how to determine which button was selected by the user in a print dialog box? Thank you! ...

What is the best way to choose a specific row with Enzyme?

We have chosen Jest for doing UI Test-Driven Development on our React application. Our component rendering structure looks like this: <Div> <Row> </Row> <ROW> <Row> <ROW> <Link> <Link> ...

Using Node.js and Express to import a simple JavaScript file as a router

Can anyone help me understand how to import the user.json json file into my user.js? I want the json file to be displayed when typing /user but I'm struggling with the new version of Node. index.js import express from 'express'; import body ...

Using PHP to send asynchronous requests to the server can greatly enhance

I have almost completed my project, but I am facing an issue with reading the data sent to the server. function main() { jQ(document).on("keyup", "form input", function () { var data = new FormData(); var value = jQ(this).val(); da ...

What is the best way to retrieve dates from a MySQL database using ExpressJS?

My current task involves retrieving the date value from a MySQL server, but upon printing the result, I encounter an error. In my code, I am able to fetch the date value, however, when attempting to print it, there seems to be an issue with the output. (F ...

An error has occurred: Noty (notification library) is not defined in this AngularJS Web Application

I am currently diving into the world of AngularJS and building a web application from scratch. As a newbie to AngularJS, I want to point out that I might be missing something crucial. An issue has arisen: After installing the Noty library (npm install no ...

Utilizing AJAX to seamlessly transfer id elements to a database

I have the following working code: <script> function displayUserData(str) { if (str=="") { document.getElementById("userDetails").innerHTML=""; return; } if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLH ...

eliminate element from array and refresh table

I am facing an issue with my code where I have an array bound to ng-repeat and a button. When the user clicks on the button, I want to remove an element from the array. Here is my current code snippet: var app=angular.module('app',[]); app.con ...

Leveraging pre-rendered HTML in Vue.js components for both parent and child elements

Currently, I am rendering all the HTML server-side and attempting to use Vue to set this HTML as the $el for two components. According to the lifecycle diagram, this should be possible. There is a parent Vue instance (which binds to #main) that contains a ...

The following middleware is not functioning properly on a local SSL server

When I run my Nextjs app without SSL using "next dev", the middleware functions as expected without any errors. However, if I attempt to run the app with SSL enabled, an empty middleware function triggers an error. The code for the middleware function (l ...

Retrieving information from a JSON output to use in an insert statement in Python

Imagine a scenario where I have a JSON structure as follows: [ { "randomcol" : "randomvarchar" } ] This JSON is generated through the following code snippet: cursor_orcl.execute(""" Select * from test_t where """) r ...

Adjusting the height of content in Angular Material 2 md-tab

I've recently started working with angular material and I'm facing an issue while trying to implement md-tab into my application. The problem is that I can't seem to style my tab content to take up the remaining height of the screen. Could s ...

Exclude the key-value pair for any objects where the value is null

Is there a way to omit one key-value pair if the value is null in the TypeScript code snippet below, which creates a new record in the Firestore database? firestore.doc(`users/${user.uid}`).set({ email: user.email, name: user.displayName, phone: ...

Error encountered: Jquery counter plugin Uncaught TypeError

I am attempting to incorporate the JQuery Counter Plugin into my project, but I keep encountering an error: dashboard:694 Uncaught TypeError: $(...).counterUp is not a function <!DOCTYPE html> <html lang="en"> <head> <script src ...

Tips for displaying an HTML page using JavaScript

In my project, I am working with an .html file (File X) that needs to immediately open another .html file (File Y) based on a certain value. Could someone provide guidance on the best way to achieve this using JavaScript? Additionally, I would like the pa ...

Jerky visuals on the canvas

My canvas animation runs smoothly in Chrome, but it's as choppy as a bad haircut in Firefox. Surprisingly, the code is not even that complex. Is there anything in my code that could be causing this slowdown? Here is the jsfiddle link for reference: h ...

A little brain teaser for you: Why is this not functioning properly on Google Chrome?

Have you noticed that the code below works perfectly in Firefox, but fails in Chrome when trying to 'post' data? $("a").click(function() { $.post("ajax/update_count.php", {site: 'http://mysite.com'}); }); Hint: Make sure you are us ...