The functionality of JSON.stringify does not take into account object properties

Check out the example on jsfiddle at http://jsfiddle.net/frigon/H6ssq/

I have encountered an issue where JSON.stringify is ignoring certain fields. Is there a way to make JSON.stringify include them in the parsing?

In the provided jsfiddle code...

<script src="http://cdn.kendostatic.com/2012.2.710/js/kendo.all.min.js"></script>
    <script>
    var model = kendo.data.Model.define({id: "ID", fields: {"Name":{type: "string"}}});
    var obj = new model();
    obj.set("Name","Johhny Foosball");
    document.write("<br />obj.dirty property exists: ");
    document.write(obj.dirty);
    document.write("<br/>obj.uid property exists: ");
    document.write(obj.uid);
    document.write("<br/>However, they are not included in JSON.stringify():<br/>");    
    document.write(JSON.stringify(obj));
</script>

you will see the following output:

obj.dirty property exists: true

obj.uid property exists: b4af4dfc-9d94-4a2d-b286-d6f4cbc991d8

However, they are not included in JSON.stringify():

{"ID":"","Name":"Johhny Foosball"}

Answer №1

When an item possesses its own toJSON() method, JSON.stringify() will utilize the object that is returned from that method to stringify it. The kendo.data.Model has its own custom toJSON() method which solely returns the properties specified on the model. This explains why certain values (such as dirty, id, uid) are not visible in the string result.

"If the stringify method encounters an object with a toJSON method, it will invoke that method and stringify the resultant value. This grants an object the ability to specify its own JSON representation."

If you require all properties to be present on the object, you can consider this alternative approach:

var model = kendo.data.Model.define({
    id: "ID",
    fields: {
        "Name": { type: "string" }
    }
});
var obj = new model();
obj.set("Name","Johhny Foosball");    
var newObj = $.extend({}, obj);
delete newObj.toJSON;
document.write(newObj.dirty);
document.write(JSON.stringify(newObj));

..and view the updated fiddle here.

Essentially, I utilized jQuery.extend to duplicate the object and then removed the toJSON function. Proceed with caution! :)

Answer №2

For those utilizing NodeJS, consider using the following code snippet:

import * as utility from 'util';
utility.inspect(data)

as an alternative to JSON.stringify.

Answer №3

One way to handle this issue is by utilizing a custom JSON.stringify function for dealing with Sequelize models. This approach involves serializing the object before making any modifications:

serializedObj = JSON.stringify(obj) // using a specialized JSON.stringify implementation
obj = JSON.parse(serializedObj) // only includes properties defined in the model's schema
obj.dirty = "whatever";
finalObj = JSON.stringify(obj); // now the changes are reflected without relying on a custom JSON.stringify method

Answer №4

Having faced a similar issue, I was delighted to find a workaround for retrieving the original object without all the unnecessary additional properties added by kendo:

cleanObj = JSON.parse(JSON.stringify(kendoData));

This problem arose when I had to transfer the selected item from a kendo tree to a directive for formatting JSON data. Much to my dismay, keno had already altered my initial object.

<div kendo-tree-view="treeView" k-data-source="dataTree" k-on-change="selectedItem=chosenItem">
    {{chosenItem.text}}
</div>

<json-display open="1" jsonData="selectedItem"></json-display>

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

Is there a way to deliver information to a specific element on a client's HTML page?

My current project involves using Node.js to serve a webpage that collects user inputs and stores them in a mongodb server. The web page also displays these user inputs. I am trying to determine the best way to pass the user inputs from node.js to the < ...

Information on the Manufacturer of Devices Using React Native

Struggling to locate the device manufacturer information. Using the react-native-device-info library produces the following output. There seems to be an issue with handling promises. I need to store the device manufacturer value in a variable. const g ...

Navigating in a Curved Path using Webkit Transition

Currently, I am working on a simple project to learn and then incorporate it into a larger project. I have a basic box that I want to move from one position to another using CSS webkit animations and the translate function for iOS hardware acceleration. I ...

What could be causing the lack of animation in W3schools icons?

I've followed the steps provided and even attempted to copy and paste them. However, I'm experiencing an issue where the animation doesn't fully execute. Instead of the bars turning into an X shape, they reset halfway through the animation. ...

Incorporating Stripe into your Next.js 13 application: A step-by-step guide

Struggling to incorporate Stripe into my Next.js 13 app for a pre-built checkout form. So far, all attempts have fallen short. Seeking assistance from anyone who has conquered this integration successfully. Any tips or guidance would be highly valued. Pl ...

Is there anyone who can provide a comprehensive explanation for what is going on here?

{ // Let's figure out how to launch my HTML file as a webpage in Chrome. "version": "0.2.0", "configurations": [ { "type": "pwa-chrome", &q ...

Extracting information from HTML and transferring it to Javascript using jQuery

My goal is to utilize jsGrid for showcasing database data without repeating code extensively. I aim to generate separate grids for each <div> with a specific id while passing on relevant values accordingly. To clarify my objective, here's a sni ...

What is the most effective way to populate an element using jQuery?

When you click a button with jQuery, I am generating a modal (Bootstrap modal) as a string. This modal has two option classes: Call Today and Call Tomorrow, which seems fine so far. Upon clicking the button, the modal is created, prompting me to add two a ...

"Engaging with the touchscreen inhibits the triggering of click

Within this div, I have implemented touch-action:pan-y;. Surrounding this div is an anchor tag. If you click on the div, the link will successfully redirect. However, if you swipe on the div and then click, the link won't work on the first attempt bu ...

The process of deserializing WCF JSON data using JavaScriptSerializer is being delayed

I've been working on deserializing a large JSON response in a WCF application using a generic method. However, the process is taking an unexpectedly long time to handle approximately 5 MB of data. During program execution, I consistently encounter a ...

Increased/Decreased impact

Can someone explain how the "Tell me more" effect is achieved on the website linked below? I'm familiar with the read more/less effect in jQuery, but what intrigues me is that the page cannot be scrolled unless the button is clicked. Here is the link ...

Having difficulty implementing a personalized color scheme for the mui component

Attempting to set the background color as midnightBlue but encountering an error: Error: Cannot read properties of undefined (reading '100') Upon reviewing the syntax, no errors were found. Perhaps this issue stems from a dependency problem? ...

Identify and emphasize fields that contain identical, non-empty values

I am attempting to compare the values of textboxes and highlight them if they are the same, excluding any textboxes that are empty. Feel free to view an example on this JSFiddle link: http://jsfiddle.net/qjqa1et2/61/ Below is the jQuery code I am current ...

What is the process for debugging a project that is not the "main" one?

I am facing an issue with Visual Studio Code where I have two directories in my workspace, both of which are node.js projects. However, I am only able to launch one of them for debugging. Even though both folders have a launch.json file, only the first fol ...

Load the content of the dialog and transfer variables

After struggling for days, I am still unable to find a solution to my current dilemma. In my database, there are approximately 1300 items each with its own unique "id", a corresponding "name", and a property called "enabled". My goal is to display links t ...

Material UI Date-Picker: Placeholder for Month Abbreviation with 3 Letters set as "MMMM" instead of the usual "MMM"

I'm currently using the most recent version of @mui/x-date-pickers (6.16.0). In my code snippet below, I have set the format of the text field input to be in "MMM DD, YYYY" style. However, when the date picker field is empty, the placeholder text disp ...

The functionality of the Ajax script seems to be optimized for Firefox browsers exclusively, as it is encountering issues with compatibility on other

My code works perfectly in Firefox, but I'm encountering an issue in all other browsers. Specifically, I'm getting the error message "SyntaxError: JSON Parse error: Unexpected EOF" on line if (this.readyState == 4 && this.status == 200). ...

React js: Changing Material-UI functional code to class component results in TypeError

After utilizing the material ui login page code, I discovered that it is a functional component. To meet my specific requirements, I decided to convert it into a class component. However, during the conversion process, an error was encountered: "Cannot ass ...

Preventing special characters in an input field using Angular

I am trying to ensure that an input field is not left blank and does not include any special characters. My current validation method looks like this: if (value === '' || !value.trim()) { this.invalidNameFeedback = 'This field cannot ...

What is the best way to arrange this object alphabetically by name using Angular?

My client is in need of an AngularJS application that will interact with an API from an existing app. The API returns JSON data structured like the following: { "groups":{ "60":{ "name":"History" }, "74":{ "n ...