JSON.stringify 忽略对象属性 [英] JSON.stringify is ignoring object properties
问题描述
参见 jsfiddle 示例 http://jsfiddle.net/frigon/H6ssq/
See the jsfiddle example http://jsfiddle.net/frigon/H6ssq/
出于某种原因,JSON.stringify 忽略了某些字段.有没有办法强制 JSON.stringify 解析它们?
For some reason there are fields that JSON.stringify is ignoring. Is there a way to force JSON.stringify to parse them?
正如 jsfiddle 所示...这段代码...
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>
将输出:
obj.dirty 属性存在:true
obj.dirty property exists: true
obj.uid 属性存在:b4af4dfc-9d94-4a2d-b286-d6f4cbc991d8
obj.uid property exists: b4af4dfc-9d94-4a2d-b286-d6f4cbc991d8
但它们没有在 JSON.stringify() 中显示:
But they dont show in JSON.stringify():
{"ID":"","Name":"约翰尼足球"}
{"ID":"","Name":"Johhny Foosball"}
推荐答案
当一个对象有自己的 toJSON()
实现时,JSON.stringify()
使用该对象从该方法返回并将其字符串化.kendo.data.Model
定义了它自己的 toJSON()
方法,该方法只返回在模型上定义的属性,这就是为什么您没有看到其他值(例如 dirty
, id
, uid
) 在字符串结果中.
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.
"如果 stringify 方法看到一个包含 toJSON 方法的对象,它会调用该方法,并将返回的值字符串化.这允许对象确定自己的 JSON 表示."
"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));
..和更新的小提琴.
基本上我使用 jQuery.extend
来克隆对象,然后删除了 toJSON
函数.使用风险自负!:)
Basically I used jQuery.extend
to clone the object then deleted the toJSON
function. Use at your own risk! :)
这篇关于JSON.stringify 忽略对象属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!