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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 00:08:05  来源:igfitidea点击:

JSON.stringify ignore some object members

javascriptjqueryjsonstringify

提问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 };

more: http://www.json.org/js.html

更多:http: //www.json.org/js.html

回答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"]) 它比上面建议的更好匹配!