javascript JSON.stringify 忽略一些对象成员
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7437709/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JSON.stringify ignore some object members
提问by Moz
Heres a simple example.
这是一个简单的例子。
function Person() {
this.name = "Ted";
this.age = 5;
}
persons[0] = new Person();
persons[1] = new Person();
JSON.stringify(persons);
If I have an arrayof Person objects, and I want to stringify them. How can I return JSON with only the name variable.
如果我有一个Person 对象数组,并且我想对它们进行字符串化。如何仅使用 name 变量返回 JSON。
The reason for this is, I have large objects with recursive references that are causing problems. And I want to remove the recursive variables and others from the stringify process.
这样做的原因是,我有带有递归引用的大对象,这导致了问题。我想从字符串化过程中删除递归变量和其他变量。
Thanks for any help!
谢谢你的帮助!
采纳答案by Kevin B
I would create a new array:
我会创建一个新数组:
var personNames = $.map(persons,function(person){
return person.name;
});
var jsonStr = JSON.stringify(personNames);
回答by lordvlad
the easiest answer would be to specify the properties to stringify
最简单的答案是指定要字符串化的属性
JSON.stringify( persons, ["name"] )
another option would be to add a toJSON method to your objects
另一种选择是向对象添加 toJSON 方法
function Person(){
this.name = "Ted";
this.age = 5;
}
Person.prototype.toJSON = function(){ return this.name };
回答by user113716
If you're only supporting ECMAScript 5 compatible environments, you could make the properties that should be excluded non-enumerableby setting them using Object.defineProperty()
[docs]or Object.defineProperties()
[docs].
如果您仅支持 ECMAScript 5 兼容环境,则可以通过使用[docs]或[docs]设置应排除的属性来使它们不可枚举。Object.defineProperty()
Object.defineProperties()
function Person() {
this.name = "Ted";
Object.defineProperty( this, 'age', {
value:5,
writable:true,
configurable:true,
enumerable:false // this is the default value, so it could be excluded
});
}
var persons = [];
persons[0] = new Person();
persons[1] = new Person();
console.log(JSON.stringify(persons)); // [{"name":"Ted"},{"name":"Ted"}]
回答by moshe beeri
see this postspecify the field you'd like to include. JSON.stringify(person,["name","Address", "Line1", "City"]) it is match better then what suggested above!
请参阅此帖子指定您要包含的字段。JSON.stringify(person,["name","Address", "Line1", "City"]) 它比上面建议的更好匹配!