What does JSON.stringify() does with functions in an object?

Assuming a Javascript object has a function:

function Foo() {
    this.a = 32;
    this.bar = function (){
        alert("Hello World!");
    }
}

How does JSON.stringify() deal with the bar function? Is it just ignored? Is this standard practice? What does JSON converts and doesn't convert into the Json string?

Rem: I don't know why people downvoted my question, it is obvious one should not stringify an object with a function. I was just trying to understand the default behavior.

Upvotes: 1

Views: 2167

Answers (1)

Qantas 94 Heavy
Qantas 94 Heavy

Reputation: 16020

JSON.stringify simply changes functions passed into null if passed into an array, and does not include the property in at all if in an object. It makes no attempt to replicate the function, not even in string form.

For example, see this:

JSON.stringify([function () {}]); // "[null]"
JSON.stringify({ x: function () {} }); // "{}"

If you attempt to stringify a function itself, it's not a valid JSON value, which means that JSON.stringify can't make a valid JSON string:

JSON.stringify(function () {}); // undefined

This is specified as part of the ECMAScript specification, though the actual wording of it is rather complex. However, a note is included that summarises this:

NOTE 5

Values that do not have a JSON representation (such as undefined and functions) do not produce a String. Instead they produce the undefined value. In arrays these values are represented as the String null. In objects an unrepresentable value causes the property to be excluded from stringification.

Upvotes: 1

Related Questions