You can use JSON.stringify with a replacer like:

JSON.stringify({
   color: 'red',
   doSomething: function (arg) {
        alert('Do someting called with ' + arg);
   }
}, function(key, val) {
        return (typeof val === 'function') ? '' + val : val;
});
Answer from CD.. on Stack Overflow
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › JSON › stringify
JSON.stringify() - JavaScript | MDN
The value to convert to a JSON string. ... A function that alters the behavior of the stringification process, or an array of strings and numbers that specifies properties of value to be included in the output. If replacer is an array, all elements in this array that are not strings or numbers (either primitives or wrapper objects), including Symbol values, are completely ignored.
🌐
W3Schools
w3schools.com › js › js_json_stringify.asp
JSON.stringify()
JSON.stringify() can not only convert objects and arrays into JSON strings, it can convert any JavaScript value into a string.
Top answer
1 of 6
15

You can use JSON.stringify with a replacer like:

JSON.stringify({
   color: 'red',
   doSomething: function (arg) {
        alert('Do someting called with ' + arg);
   }
}, function(key, val) {
        return (typeof val === 'function') ? '' + val : val;
});
2 of 6
9

A quick and dirty way would be like this:

Object.prototype.toJSON = function() {
  var sobj = {}, i;
  for (i in this) 
    if (this.hasOwnProperty(i))
      sobj[i] = typeof this[i] == 'function' ?
        this[i].toString() : this[i];

 return sobj;

};

Obviously this will affect the serialization of every object in your code, and could trip up niave code using unfiltered for in loops. The "proper" way would be to write a recursive function that would add the toJSON function on all the descendent members of any given object, dealing with circular references and such. However, assuming single threaded Javascript (no Web Workers), this method should work and not produce any unintended side effects.

A similar function must be added to Array's prototype to override Object's by returning an array and not an object. Another option would be attaching a single one and let it selectively return an array or an object depending on the objects' own nature but it would probably be slower.

function JSONstringifyWithFuncs(obj) {
  Object.prototype.toJSON = function() {
    var sobj = {}, i;
    for (i in this) 
      if (this.hasOwnProperty(i))
        sobj[i] = typeof this[i] == 'function' ?
          this[i].toString() : this[i];

    return sobj;
  };
  Array.prototype.toJSON = function() {
      var sarr = [], i;
      for (i = 0 ; i < this.length; i++) 
          sarr.push(typeof this[i] == 'function' ? this[i].toString() : this[i]);

      return sarr;
  };

  var str = JSON.stringify(obj);

  delete Object.prototype.toJSON;
  delete Array.prototype.toJSON;

  return str;
}

http://jsbin.com/yerumateno/2/edit

🌐
DigitalOcean
digitalocean.com › community › tutorials › js-json-parse-stringify
How To Use JSON.parse() and JSON.stringify() | DigitalOcean
November 24, 2021 - JSON.stringify() takes a JavaScript object and transforms it into a JSON string.
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › javascript-json-stringify-method
JavaScript JSON stringify() Method - GeeksforGeeks
July 11, 2025 - The JSON.stringify() method in JavaScript is used to convert JavaScript objects into a JSON string.
🌐
V8
v8.dev › blog › json-stringify
How we made JSON.stringify more than twice as fast · V8
At the end, the final result is constructed by simply concatenating the output from the initial one-byte stringifier with the output from the two-byte one. This strategy ensures we stay on a highly-optimized path for the common case, while the transition to handling two-byte characters is lightweight and efficient. Any string in JavaScript can contain characters that require escaping when serializing to JSON (e.g.
🌐
Udacity
udacity.com › blog › 2021 › 04 › javascript-json-stringify.html
Converting Javascript Objects into Strings with JSON.stringify() | Udacity
September 27, 2022 - JSON.stringify() converts Javascript objects into JSON strings. It can manage many types of data type conversion, and you can also add special conversions.
🌐
DhiWise
dhiwise.com › post › javascript-essentials-detailed-exploration-of-json-stringify
Exploring JSON Stringify: An In-Depth Exploration
September 29, 2023 - JSON Stringify is a method in JavaScript that converts JavaScript objects into JSON strings. Learn about JSON Stringify its syntax, and its parameters.
Find elsewhere
🌐
ReqBin
reqbin.com › code › javascript › wqoreoyp › javascript-json-stringify-example
How to stringify a JavaScript object to JSON string?
The JSON.stringify(value, replacer, space) method converts JavaScript objects to a JSON string. The resulting JSON string is a JSON-formatted or serialized object that can be sent over the network or stored on a disk.
🌐
W3Schools
w3schools.com › jsref › jsref_stringify.asp
JavaScript JSON stringify() Method
The JSON.stringify() method converts JavaScript objects into strings.
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › JSON › parse
JSON.parse() - JavaScript | MDN
In order for a value to properly round-trip (that is, it gets deserialized to the same original object), the serialization process must preserve the type information. For example, you can use the replacer parameter of JSON.stringify() for this purpose:
🌐
HostingAdvice
hostingadvice.com › home › how-to
JavaScript "Object to String" Using JSON.stringify()
March 24, 2023 - This can be useful for things like: ... an object to a string is: JSON.stringify(value) The full syntax is: JSON.stringify(value[, replacer[, space]]) Note: For the purposes of this article, whenever we say “object” we mean ...
🌐
ZetCode
zetcode.com › javascript › json-stringify
JavaScript JSON.stringify - Converting Objects to JSON
Understand how to use JSON.stringify in JavaScript to convert objects into JSON strings, with examples and explanations.
🌐
MDN
mdn2.netlify.app › en-us › docs › web › javascript › reference › global_objects › json › stringify
JSON.stringify() - JavaScript | MDN
The JSON.stringify() method converts a JavaScript object or value to a JSON string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified.
🌐
JavaScript.info
javascript.info › tutorial › the javascript language › data types
JSON methods, toJSON
The idea is to provide as much power for replacer as possible: it has a chance to analyze and replace/skip even the whole object if necessary. The third argument of JSON.stringify(value, replacer, space) is the number of spaces to use for pretty formatting.
🌐
freeCodeCamp
freecodecamp.org › news › json-stringify-example-how-to-parse-a-json-object-with-javascript
JSON Stringify Example – How to Parse a JSON Object with JS
January 5, 2021 - Luckily, this works the same way as in the browser – just use JSON.stringify() to convert JavaScript object literals or arrays into a JSON string:
🌐
Reddit
reddit.com › r/javascript › [askjs] petition: make json.stringify use any object's tostring method internally!
r/javascript on Reddit: [AskJS] PETITION: Make JSON.stringify use any object's toString method internally!
January 3, 2024 -

What do you guys think? Should I make an official proposal? What would be the best way to make such spec proposal?

And tell me what you think! The idea is for any object's toString method override the way JSON.stringify creates the string. For example:

var vec =
{
    x: 0,
    y: 0,
    toString() => `[${this.x},${this.y}]`
}

JSON.stringify(vec) //will return: '[0,0]'

This way I won't need to use a custom stream to alter a big object when converting it to JSON!

Or would you say this is very unnecessary, even if an easy thing to add to JS?