为什么JSON.stringify显示的对象属性是函数? [英] Why doesn't JSON.stringify display object properties that are functions?

查看:365
本文介绍了为什么JSON.stringify显示的对象属性是函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么JSON.stringify()不显示prop2?

  var newObj = {
prop1:true ,
prop2:function(){
returnhello;
},
prop3:false
};

alert(JSON.stringify(newObj)); // prop2似乎缺少

alert(newObj.prop2()); // prop2返回hello

(newObj中的var成员){
alert(member +=+ newObj [member]); //显示prop1,prop2,prop3
}

JSFIDDLE: http://jsfiddle.net/egret230/efGgT/

解决方案

因为 JSON 不能存储函数。根据规范,一个值必须是以下之一:

有效的JSON值http://json.org/value.gif






请注意,代码将使得 JSON.stringify

 函数注意到的函数。 prototype.toJSON = function(){returnUnstorable function} 


Why doesn't JSON.stringify() display prop2?

var newObj = {
  prop1: true,
  prop2: function(){
    return "hello";
  },
  prop3: false
};

alert( JSON.stringify( newObj ) ); // prop2 appears to be missing

alert( newObj.prop2() ); // prop2 returns "hello"

for (var member in newObj) {
    alert( member + "=" + newObj[member] ); // shows prop1, prop2, prop3
}

JSFIDDLE: http://jsfiddle.net/egret230/efGgT/

解决方案

Because JSON cannot store functions. According to the spec, a value must be one of:

Valid JSON values http://json.org/value.gif


As a side note, this code will make the functions noticed by JSON.stringify:

Function.prototype.toJSON = function() { return "Unstorable function" }

这篇关于为什么JSON.stringify显示的对象属性是函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆