Why does serializing a JavaScript Object to JSON result in "{}"?

Hello fellow developers,

I'm currently working on setting up a LocalStorage feature for my web application.

One issue I've come across is that all objects in the Model abstraction layer need to be serialized.

I understand that functions aren't included in the JSON conversion of an object.

I was considering using the first option mentioned here, which involves creating a 'static' method to return a new object with functions.

However, even the non-function members of the objects are not being converted properly.

For instance, when doing divvie.textContent = JSON.stringify(coffee);, divvie.textContent ends up as "{}".

Why is this happening? What am I missing?

Here's some sample code similar to what I'm experiencing:


var coffee = new Coffee("0001", "DE Red Coarse", "Douwe Egberts, red & coarse grounded.");
coffee.addSugarCube("0x0F_BROWN", "15");
coffee.addSugarCube("0x0C_WHITE", "12");

var divvie = document.getElementById("run");
divvie.textContent = JSON.stringify(coffee);
</script>
</body>
</html>

/**
 * @class A representation of a coffee
 *
 * @param {String} id
 * @param {String} name
 * @param {String} description
 * @returns {Coffee}
 */
function Coffee(id, name, description) {
    var sugarCubes = new Array();
    
    var maxAmountOfSweetness = 0;

    // Rest of the Coffee class methods...

}

/**
 * @class A representation of a sugar cube
 *
 * @param {String} id
 * @param {Number} amountOfSweetness
 * @returns {SugarCube}
 */
function SugarCube(id, amountOfSweetness) {

    // SugarCube class methods...

}

Answer №1

Instances created by the Coffee constructor only have methods as properties, which do not have a JSON representation due to being functions. The data is stored in variables or parameters within closures. Since these are not actual properties, they are not meant for JSON.

To achieve the expected behavior, one option is to either implement a custom toJSON method or transfer the data from variables to properties.

For instance, utilizing properties:

function Coffee(id, name, description) {
    this.id = id;
    this.name = name;
    this.description = description;
    this.sugarCubes = [];
    this.maxAmountOfSweetness = 0;
}
// Methods can be moved to the prototype
Coffee.prototype = {
    getId: function () {return this.id;}
    // more methods

};
// Instances of Coffee can now be converted to JSON

You may have used var to conceal the data so it could only be accessed through methods. Another approach is adding a new method for converting it to JSON, like this:

// within Coffee
this.toJSON = function (a, b) {
    var o = {
        id: id,
        name: name
        // and so on
    };
    return JSON.stringify(o, a, b);
};

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

"Exploring the capabilities of Rxjs ReplaySubject and its usage with the

Is it possible to utilize the pairwise() method with a ReplaySubject instead of a BehaviorSubject when working with the first emitted value? Typically, with a BehaviorSubject, I can set the initial value in the constructor allowing pairwise() to function ...

What is the method for viewing the content within div tags on an apex page?

Locationbox is a system outside of Salesforce, similar to Google Maps. An example can be viewed here; I am aiming to integrate it into the Salesforce platform. The first script tag fetches JavaScript code from the Locationbox service. Once the startup() f ...

What is the reason behind Visual Studio intellisense not displaying the methods of XMLHttpRequest objects?

Why am I unable to access the open and send methods of the XMLHttpRequest object in Visual Studio's Intellisense? var httprequest = new XMLHttpRequest(); httprequest. I cannot see the methods in Intellisense after the dot. ...

Discover how to retrieve service response data from an API and populate it into the Select Option with Angular 2

Api.services.ts getListOfNames() { return this.http.get(this.BaseURL + 'welcome/getnama') .pipe(map(response => { return response; })); } After making the API call, I receive the following resp ...

Invalid Data Pusher for User Information in Next JS

Hello everyone, I've been practicing using Pusher with Next.js but encountered an issue where it's showing Error: Invalid user data: 'presence-channel' and I can't seem to solve it no matter how hard I try. Could someone please he ...

What is the best way to activate CSS filters on VueJS once the project has been compiled?

While working on a Node server locally, my SVG filter functions properly. However, once I build the project and run it on a server, the filter stops working. This VueJS project is utilizing Webpack as its build tool. The process of building the app invol ...

“What is the most effective way to verify the presence of an element within a numerical array using Twig

If we have an array stored in a variable (let's name it arr) in Twig and it looks like this: foo: [ { title: 'foo', id: 1 }, { title: 'bar', id: 2 }], bar: [ { some: 23, required: true }, { some: 12, ...

Error: The property 'case sensitive routing' cannot be accessed because it is undefined

Task at hand: Running ExpressJS port using Node.js, nodemon, and lib. Operating System: Windows 10 Home x64 Node.JS Version: Lts The Challenge: Getting the ExpressJS port to run successfully. Current Issue: Encountering an internal file error, potentiall ...

The presence of ng-show dynamically adjusts the minimum height of a div element

I am encountering an issue with a div that has the class of wrapper. Inside this div, there is a parent div with the class of content-wrapper. The wrapper div includes a conditional directive ng-show which toggles between displaying or hiding its content. ...

Insert HTML code that is activated when the selection is modified

I have a simple dropdown menu in my HTML code. HTML <select name="breed" onchange="breedChanged()"> <?php while ($row = gdrcd_query($result, 'fetch')){ ?> <option value="<?php echo $row['id_breed']; ?& ...

Encountering ReferenceError when attempting to declare a variable in TypeScript from an external file because it is not defined

Below is the typescript file in question: module someModule { declare var servicePort: string; export class someClass{ constructor(){ servicePort = servicePort || ""; //ERROR= 'ReferenceError: servicePort is not defined' } I also attempted t ...

Maintain checkbox state through page reloads using ajax

Currently, I am troubleshooting a script that is intended to keep checkbox values checked even after the page is reloaded or refreshed. The code snippet below was implemented for this purpose, but unfortunately, it doesn't seem to be functioning corre ...

Split total based on checkboxes toggled with JavaScript

I'm facing a challenge. I have a total sum of donations collected, for example, 10€. Additionally, there are various NGOs that one can select to donate to. Individuals have the option to toggle on/off which NGO's they wish to contribute toward ...

Retrieve the content from paginated pages using ajax, apply a filter to it, and then add it to the existing page

My blog needs more functionality and I want to avoid using paginated pages. My idea was to extract content from these paginated pages through ajax, filter it, and add it to a specific div element. I'm not completely confident if I am on the right tra ...

The form submission feature is malfunctioning due to JavaScript issues

I have forms that allow file uploads (images), and I am trying to restrict the size of those images to 500KB. However, for some reason, the forms are not submitting and I am unsure why. Below is the jQuery code: $('form').on('submit', ...

Creating a test suite with Jasmine for an Angular ui-grid component compiled without using $scope

I have encountered an issue while using $compile to compile a ui-grid for Jasmine testing. Initially, everything worked smoothly when I passed $scope as a parameter to the controller. However, I am now transitioning to using vm, which has resulted in $comp ...

Do you need assistance with downloading files and disconnecting from clients?

When looking at the code snippet below: async function (req, res, next) { const fd = await fs.open("myfile.txt") fs.createReadStream(null, { fd, autoClose: false }) .on('error', next) .on('end', () => fs.close(fd)) . ...

Passing component properties using spaces in VueJS is a simple and effective

I am encountering an issue where I want to pass component props from my view, but I am facing a challenge due to the presence of a space in the value. This causes Vue to return the following error: vendor.js:695 [Vue warn]: Error compiling template: - inva ...

I have exhausted all options trying to filter a 2D array in JavaScript

The 2D array provided is formatted as follows : [[ONE,1],[QUARTER,0.25],[QUARTER,0.25]] The desired output should be : [[ONE,1],[QUARTER,0.5]] An attempt was made using array.IndexOf but did not yield the expected result ONE,1,QUARTER,0.25,QUARTER,0.2 ...

Enhancing a specific element in a view using Node.js alongside Express and EJS

My goal is to modify value2 on the server side and update the view accordingly. The question at hand is: How can I efficiently refresh the view with only the new value2? Server: var express = require("express"); var app = express(); app.set('view ...