JSON.stringify忽略一些对象成员

Moz*_*Moz 11 javascript jquery json stringify

这是一个简单的例子.

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

persons[0] = new Person();
persons[1] = new Person();
JSON.stringify(persons);
Run Code Online (Sandbox Code Playgroud)

如果我有一个Person对象数组,我想将它们字符串化.如何只返回名称变量的JSON.

原因是,我有大型对象的递归引用导致问题.我想从stringify过程中删除递归变量和其他变量.

谢谢你的帮助!

lor*_*lad 25

最简单的答案是指定stringify的属性

JSON.stringify( persons, ["name"] )
Run Code Online (Sandbox Code Playgroud)

另一种选择是向对象添加toJSON方法

function Person(){
  this.name = "Ted";
  this.age = 5;      
}
Person.prototype.toJSON = function(){ return this.name };
Run Code Online (Sandbox Code Playgroud)

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


use*_*716 17

如果您只支持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
    });
}
Run Code Online (Sandbox Code Playgroud)
var persons = [];

persons[0] = new Person();
persons[1] = new Person();

console.log(JSON.stringify(persons));  // [{"name":"Ted"},{"name":"Ted"}]
Run Code Online (Sandbox Code Playgroud)


use*_*654 3

我会创建一个新数组:

var personNames = $.map(persons,function(person){
  return person.name;
});
var jsonStr = JSON.stringify(personNames);
Run Code Online (Sandbox Code Playgroud)