JSON.stringify is ignoring object properties

╄→гoц情女王★ 提交于 2019-11-30 22:26:09

问题


See the jsfiddle example http://jsfiddle.net/frigon/H6ssq/

For some reason there are fields that JSON.stringify is ignoring. Is there a way to force JSON.stringify to parse them?

As the jsfiddle shows... this 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/>But they dont show in JSON.stringify():<br/>");    
    document.write(JSON.stringify(obj));
</script>

will output:

obj.dirty property exists: true

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

But they dont show in JSON.stringify():

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


回答1:


When an object has its own toJSON() implementation, JSON.stringify() uses the object returned from that method and stringifies that. kendo.data.Model defines it's own toJSON() method which only returns the properties defined on the model, which is why you aren't seeing other values (e.g. dirty, id, uid) in the string result.

Take a look at this article. Specifically: "If the stringify method sees an object that contains a toJSON method, it calls that method, and stringifies the value returned. This allows an object to determine its own JSON representation."

Here's an alternative if you must have all properties on the object:

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 the updated fiddle.

Basically I used jQuery.extend to clone the object then deleted the toJSON function. Use at your own risk! :)




回答2:


Somewhat relevant, as I came here looking for a solution to a similar situation: For those looking for a way to get back their original object, before kendo added all sorts of weird hidden properties to it, do:

cleanObject = JSON.parse(JSON.stringify(kendoDataItem));

I encountered this scenario when I needed to pass the selected item from the kendo tree to a json-formatter directive. But what do you know, kendo had allready messed up with my original object.

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

<json-formatter open="1" json="selectedItem"></json-formatter>


来源:https://stackoverflow.com/questions/20511421/json-stringify-is-ignoring-object-properties

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!