JSON.stringify() only allows one value parameter. How do I add more parameters to be stringified under one brace?

http.get(options, function(res){
            fs.appendFile('log.txt', JSON.stringify(res.headers, null, 4));
})

I have a question regarding the JSON.stringify() function.

I've learned that simply using the res.headers does not in fact output to JSON format.

At the moment, I am restricted to only being able to use one res.xxxxx method within JSON.stringify(). The piece of code in question is pasted above. How am I able to use more than one value? At the moment, I can only put in res.headers into the value parameter. I would also like to use res.statusCode and my own objects, all stringified under one brace {}.

The parameters of JSON.Stringify is as follows: JSON.stringify(value, [replacer], [space]);

You need to create a new js object and put res.headers into it.

var obj = {};
obj.headers = res.headers;
obj.somethingelse = somethingelse;
var string = JSON.stringify(obj);

JSON is always a single value. So the output out JSON.stringify can always only be a single value. It would make sense to have the input be a single value too. This is like asking why can't my function return two things? You can make it return some composite value, but that means you're still returning a single (composite) value. The solution here is the same, compose your input.

var reply = {
    code: res.statusCode,
    headers: parse_http_headers(res.headers),
    etc: /* etc */
};
log(JSON.stringify(reply));

Note that you must write parse_http_headers yourself.

You could always add the extra things you want to the headers object...

res.headers.statusCode = res.statusCode
JSON.stringify(res.headers, null, 4);

I don't know if there are any bad side effects if you mutate the res object in node. You might want to consider creating a shallow copy of the headers object if you are worried about that.

You could as well stringify more than only the headers part of your object:

JSON.stringify(res, …)

If you want to stringify only certain parts of your object, you can

  • filter them with the replacer function,
  • delete everything else before,
  • or build a new object to be stringified:

    JSON.stringify({
        heads: res.headers,
        …
    }, …)
    

If you'd like to flatten several objects, you can use this function.

function merge() {
  var out = {};
  insert = function(e) {
    for (var i in e) {
      if (Object.prototype.hasOwnProperty.call(e, i))
          out[i] = e[i];
    }
  };

  for (var i = 0; i < arguments.length; i++) {
    insert(arguments[i]);  
  }

  return out; 
}

var a = {'a': 'aa'};
var b = {'b': 'bb', 'bbb': 'bbbb'};
var c = {'c': 'cc'};


var combined = merge(a,b,c);