JSON.stringify ignore some object members

15,745

Solution 1

I would create a new array:

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

Solution 2

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

Solution 3

If you're only supporting ECMAScript 5 compatible environments, you could make the properties that should be excluded non-enumerable by setting them using Object.defineProperty()[docs] or Object.defineProperties()[docs].

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"}]
Share:
15,745
Moz
Author by

Moz

Updated on July 10, 2022

Comments

  • Moz
    Moz almost 2 years

    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!