0

ISSUE
I want to call JSON.stringify passing the fields I want to include in the string. One of the fields I want to include is an object. The JSON.stringify method does not include any of the fields from the object as I would have expected.

Here is a small subset of my larger object;

  var person = {
      name: "John Doe",
      Address: { Line1: "100 north main",  City: "Des Moines" },
      Phone: "555-5555"
    }

Here is the stringify method call

   console.log(JSON.stringify(person,["name","Address"]));

Here is the results

"{\"name\":\"John Doe\",\"Address\":{}}"

Here is a js bin I created - http://jsbin.com/UYOVufa/1/edit?html,console.

I could always stringify just the person.Address and combine it with another string, but it feels like overkill.

What am I missing?

Thanks,

RDotLee
  • 1,083
  • 2
  • 15
  • 32

3 Answers3

5

The JSON.stringify accepts replacer (that array...) as an argument. Note the replacer documentation:

If you return any other object, the object is recursively stringified into the JSON string, calling the replacer function on each property, unless the object is a function, in which case nothing is added to the JSON string.

(Source: https://developer.mozilla.org/en-US/docs/Using_native_JSON#The_replacer_parameter)

This will work:

JSON.stringify(person,["name","Address", "Line1", "City"])
AlonL
  • 6,100
  • 3
  • 33
  • 32
3

As mentioned above, JSON.stringfy make a recursively replacement, and just need to put the keys names to get it. But, also, is enough powerfull to make your own versions of json strings easily.

My proposal to achieve the solution you want is

JSON.stringify(person, function(k,v){
    if(k!=="Phone"){
        return v;
    }
});

The function substitutes the default replacer and lets you output whatever you want without affecting the original json object. Imagine the possibilities, greatly increases control over the output response.

DVicenteR
  • 496
  • 4
  • 7
1

It checks the field list for each key, even if it's a key in a nested object:

JSON.stringify(person, ['name', 'Address', 'Line1', 'City'])

=> "{"name":"John Doe","Address":{"Line1":"100 north main","City":"Des Moines"}}"
Jakub Roztocil
  • 15,930
  • 5
  • 50
  • 52