Unexpected behavior from JSON.stringify causing it to not return the desired objects

I have been experimenting with Node.js and Websockets lately. Making progress, but I encountered an unusual issue with JSON.stringify (client side).

I use JSON.stringify to see which object properties the server is returning.

For instance, this is the code snippet I have:

ws.onmessage = function(param1) {
    alert(JSON.stringify(param1));
}

An alert box showing {"isTrusted" : true} pops up.

Seeing this output made me think that the server did not send a message back to the client. To check, I modified the alert function to simply show

alert(param1.data);

The expected message appeared! So, my question is why didn't JSON.stringify display the data object even though it was clearly there?

Answer №1

JSON.stringify specifically includes only the own, enumerable properties of an object in the output. This is detailed in the abstract SerializeJSONObject operation in the specifications. In simpler terms, this means that any inherited properties and non-enumerable properties are excluded from the final output.

Interestingly, in the mentioned scenario, the only own, enumerable property found in the message was isTrusted.

Here's an illustrative example:

function Thingy(name, age) {
  // Set `name` as an own, enumerable property
  this.name = name;
  
  // Set `age` as an own, non-enumerable property
  Object.defineProperty(this, "age", {
    value: age
  });
}

// Establish `what` as a property that all `Thingy` instances will inherit:
Thingy.prototype.what = "evs";

// Create an instance
var t = new Thingy("foo", 42);

// Retrieve the JSON representation:
console.log(JSON.stringify(t)); // {"name":"foo"}


The key lesson to learn from this is that traditional alert-style debugging is becoming outdated in the current landscape. Instead of fumbling around blindly with alerts (or console.log), it's more effective to utilize the robust debugger integrated into your web browser. Set a breakpoint at the start of your function, and once it's triggered, view the properties of param1 in real-time. This method provides a comprehensive view of both own and inherited properties, enumerable and non-enumerable, along with their current values while your JavaScript execution is paused.

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

Error: The variable "message" has not been defined. Please define it before displaying the welcome

While I was experimenting with my welcome message and attempting to convert it into an embed, I ended up rewriting the entire code to make it compatible. However, upon completion, I encountered the error message is not defined. var welcomePath = './ ...

Creating a resilient node websocket client with enhanced security (overcoming the challenge of verifying the initial certificate)

What's Working? I successfully created a node server using WebSocket technology. I used the library WebSocket-Node and added key/cert to my HTTPS/secure websocket server as shown below: import WebSockerServer from "websocket"; import fs fro ...

My desire is for every circle to shift consecutively at various intervals using Javascript

I'm looking to draw circles in a sequential manner. I am trying to create an aimbooster game similar to . Instead of drawing all the circles at once, I want each circle to appear after a few seconds. The circles I've created currently do not g ...

Parsing UK Bank holidays data using Pandas

Having trouble reading the JSON file from this link into pandas properly : I attempted to use json_normalize and also tried opening it as a file with the standard python library, converting to dict, and then reading it into pandas. This is the result I&a ...

What steps are necessary to configure .eslintrc to identify the use of 'require'?

I recently started using ESLint and successfully integrated it with IntelliJ. Initially, ESLint did not recognize node out of the box. After consulting the documentation, I created a configuration file named .eslintrc at the project's root folder, sp ...

Validating binary tree logic operations through Json schema verification

Struggling with data validation, wondering if json schema can better suit my needs. My input: (1 or (1 and 0)) => true This input becomes a json object: [1, [1, 0]] The current schema can't handle the OR case correctly between nested data. { ...

"Exploring the World Wide Web with JavaScript and Ajax in Internet

Is there a way to include a Javascript snippet at the end of some ajax content? It seems to be functioning properly in Firefox, but when I try it in Internet Explorer, the script is printed out without being executed. <script type="text/javascript"&g ...

Steps for setting up configurations in json2csv using express

I've been trying to utilize the json2csv module to parse JSON into CSV format, as the documentation suggests that configurations such as including NULL values or setting default values are possible. However, despite my efforts, I am unable to get it t ...

Unable to launch React Native project

Error: Module Not Found Cannot find module 'C:\Users\Admin\AppData\Local\npm-cache\_npx\7930a8670f922cdb\node_modules\@babel\parser\lib\index.js'. Please make sure that your package.jso ...

Setting up jade includes with gulp-jade: A comprehensive guide

Struggling with setting up Jade includes in your gulpfile.js while using gulp-jade? Check out this link for more information. Below is a snippet from the gulpfile.js: var gulp = require('gulp'); var browserSync = require('browser-s ...

Experiencing difficulty decoding JSON output on jquarymobile's HTML page when making an Ajax request

After developing screens for my Android application using PhoneGap and jQuery Mobile, I have included the necessary JavaScript and CSS files in my HTML page: <link rel="stylesheet" href="css/jquery.mobile-1.3.1.css" /> <script src="js/jquery-1. ...

Tips for refreshing Facebook's og tags

I've been racking my brains over this issue for days, and despite the abundance of similar inquiries, I have yet to find a solution. On my blog-like website, each post requires its own title and description for Facebook articles. I know I can set the ...

Storing JSON data in a SQL database

Storing JSON in an MsSql database and passing it to Javascript via a PHP script has been working perfectly. However, when trying to include extra text that is not part of the formatting string, like d, h, a, or p characters, encountered some challenges. Lu ...

Obtaining an image from encoded JSON information

This inquiry pertains to Visual Basic .NET 2010 How do I extract the image from this encoded JSON string? What type of encoding is being used here? I'm attempting to capture a screenshot of a website using the Google PageSpeed API. "screenshot": { ...

Is it possible to execute a function once an element has finished loading?

I am facing a challenge with running the List_Sandbox functions after a specific each loop. This loop selects checkboxes that trigger a change event, rendering additional checkboxes that need to be selected. The issue arises when the List_Sandbox functio ...

What is the best way to merge multiple models in JBuilder?

I am in need of the following structure: [{model}, {model}, {other model}, ...] # for jquery ui autocomplete Is there a way to create this structure using JBuilder? It seems like with render array they have the array! method which accepts one argument - ...

Dynamically add index to attribute as it updates

Having an issue with my dynamic button element: <button v-on:click="changeRecord(element)" v-b-modal.modal-5>Aendern</button> This button is generated dynamically within a v-for loop. Instead of manually including the attribute name like v-b- ...

Tips for retrieving a local variable from inside a callback and using it outside the function

Recently, I started utilizing npm plaid and I'm looking for a way to access the variable trans outside of the plaidClient.getTransactions function. Any suggestions would be greatly appreciated. var trans; var startDate = moment().subtract(30, &apo ...

What is the best way to send a JQuery variable using JSON.stringify and retrieve it on the server-side?

I need to pass the value in JSON.stringify and receive it on the Server side. Please note: When I attempt to pass the value directly without utilizing a JQuery variable, everything works smoothly. Without using a JQuery variable (it's functional) d ...

Performing String formatting in JavaScript using an array

I've been utilizing the stringformat library to format strings in my node.js applications. var stringFormat = require('stringformat'); stringFormat.extendString(); In my current project, I'm attempting to pass an array of parameters a ...