Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON.stringify ignore some object members

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!

like image 319
Moz Avatar asked Sep 15 '11 21:09

Moz


1 Answers

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

like image 117
lordvlad Avatar answered Sep 29 '22 11:09

lordvlad