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

There seems to be an issue with Vue JS slots[name$1].every function as it is

I attempted to implement a custom isEmpty function for the Object prototype as follows: Object.prototype.isEmpty = function() { for (var key in this) { if (this.hasOwnProperty(key)) { return false } } return true } However, when tryin ...

What is the best way to arrange images in a 3 by 3 grid, beginning at position 0, using JavaScript to control navigation through button clicks?

When I click on button 1, it starts at image 1 because the counter is set to 0. Clicking on button 2 takes me to image 4 with a counter value of 3, while clicking on button 3 leads to image 7 with a counter value of 6. The process should also work in reve ...

Encountering an unexpected token ';' in a random generator while attempting to utilize an if-else statement for determining DOM manipulation

After dabbling in programming on and off for a few years, I've finally decided to dive deep with some simple personal projects. One of the tasks I'm working on is creating a randomizer for a pen and paper RPG, where it samples from an array at ra ...

What is the best way to define a variable that captures and logs the values from multiple input variables?

Hey there, I'm a new coder working on a shopping list app. I'm trying to display the input from three fields - "item", "store", and "date" - at the bottom of the page as a single line item. I attempted to do this by creating a variable called "t ...

The requested API endpoint for retrieving the name could not be found on the Express

Struggling to configure the restful API for my express app. Below is my app.js code: var express = require('express'), app = express(), bodyParser = require('body-parser'), methodOverride = require('method-override'); rout ...

Browser encountering HTTP response that has been shorted extensively

When making an HTTP post request using axios, I am encountering an issue where the body of the response is a large 4MB string. axios({ method: 'POST', url: url, data: data, headers : headers, }) .then(function (response) { co ...

The combination of NextJS and Firebase Auth using the GoogleAuthProvider is powerful

I am encountering challenges while trying to integrate firebase authentication with Google Provider in NextJS. I have set up the necessary environment variables and successfully established a connection with firebase. However, I keep running into an error ...

Struggling to locate images in Three.js

I'm facing a challenge with my Vue Cli app where I am attempting to use Three.js for rendering 3D objects within it. The issue arises when I attempt to load an image to utilize as a texture. let scene = new Three.Scene(); const spaceTexture = new Th ...

Trouble with Displaying 3rd Level JQuery Dropdown Menu

Currently working on implementing a 3 level dropdown feature. I have been using a third-party responsive menu in Opencart and it's been working well. You can see a demo of it here: Unfortunately, Opencart does not natively support 3 level categories, ...

Discover automatically generated titles for dynamic hyperlinks

I am looking to generate dynamic links for a collection of documents with varying names, such as Test, Test2, and so on. I want the link text to display as "Document TestN," where N is the specific document number. Currently, I am able to create the links ...

Combining several JSON objects into a single JSON object using JavaScript

I am in need of merging JSON objects from various sources into a single JSON object using JavaScript. For example, I have two JSON objects with different values that I need to combine and add a new value to the final result. json1= { "b":"t ...

Discover every user receiving a database object instead of individual records with mLab

While using my express application with the mLab database, I encountered an issue. When trying to find only one record, everything works fine. However, when attempting to retrieve a list of users from the database, I receive the following response. Query ...

The constantly persisted caching issue persistently plagues the index method that specifically caters to

I have a Ruby on Rails website and I am facing an issue with caching the JSON data. In my DefinitionsController, I have set up a cache for the index action using the caches_page method. The index action responds to json format and renders the @something va ...

Variables in the $scope object in AngularJS

Within my $scope in angularJS, I am working with two types of variables. 1). $scope.name and $scope.title are linked to input boxes in the UI html code. 2). On the other hand, $scope.sum and $scope.difference are internally used within my JS code. I need ...

Error Encountered - Node.js application experiencing issues in passport login functionality

I'm in the process of developing a login application using nodejs and incorporating passport js for authentication. The app is connected to a local MySql database and utilizes sequelize as its ORM library. Within my user model, I've implemented ...

Sharing information between External JavaScript and React JS/Redux

Incorporating React-redux into an externalJs application (built on a custom JS framework) has posed a challenge for me. I am trying to initialize data for the Redux store from externalJS, but it seems that the external script is unable to access the React ...

Fetching a substantial amount of data via AJAX to generate a graph

Currently, I am in the process of developing a server that will supply data and information to both a web client and a mobile client in the second phase. One of the key features is displaying this data on a graph, such as showing the price of a stock over ...

Change the color of the border to match the background color

I have a parent container with a unique background color. Inside the parent container, there is an unordered list (ul) with multiple list items (li), each having a distinct color and a brighter border color. Now, I am looking to extract the border color of ...

An easy way to adjust the date format when linking a date in ng-model with md-datepicker

<md-input-container> <label>Scheduled Date</label> <md-datepicker ng-model="editVersionCtrl.selectedPlannedDate" ng-change="editVersionCtrl.checkPlannedDate()"> </md-datepicker> </md-input-container> ...

Limit the radio button to being clickable

Ugh, I'm really struggling with this. I want to create a quiz where only the radio button is clickable, not the text itself. Can anyone help me figure out how to do this? I have two codes below that I don't quite understand. I'll include th ...