JSON.stringify ignore some object members

Moz picture Moz · Sep 15, 2011 · Viewed 15.1k times · Source

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 array of Person objects, and I want to stringify them. How can I return JSON with only the name variable.

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!

Answer

lordvlad picture lordvlad · Dec 30, 2012

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

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

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