12

这是一个简单的例子。

function Person() {
  this.name = "Ted";
  this.age = 5;
}

persons[0] = new Person();
persons[1] = new Person();
JSON.stringify(persons);

如果我有一个Person 对象数组,并且我想对它们进行字符串化。如何仅返回带有 name 变量的 JSON。

这样做的原因是,我有带有递归引用的大型对象,这些对象会导致问题。我想从字符串化过程中删除递归变量和其他变量。

谢谢你的帮助!

4

4 回答 4

29

最简单的答案是指定要字符串化的属性

JSON.stringify( persons, ["name"] )

另一种选择是将 toJSON 方法添加到您的对象

function Person(){
  this.name = "Ted";
  this.age = 5;      
}
Person.prototype.toJSON = function(){ return this.name };

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

于 2012-12-30T19:03:32.583 回答
18

如果您只支持 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"}]
于 2011-09-15T21:46:04.007 回答
3

我会创建一个新数组:

var personNames = $.map(persons,function(person){
  return person.name;
});
var jsonStr = JSON.stringify(personNames);
于 2011-09-15T21:39:05.443 回答
-1

请参阅此帖子 指定您要包含的字段。JSON.stringify(person,["name","Address", "Line1", "City"]) 它比上面建议的匹配更好!

于 2015-08-23T18:50:31.747 回答