11

Why doesn't JSON.stringify() display prop2?

var newObj = {
  prop1: true,
  prop2: function(){
    return "hello";
  },
  prop3: false
};

alert( JSON.stringify( newObj ) ); // prop2 appears to be missing

alert( newObj.prop2() ); // prop2 returns "hello"

for (var member in newObj) {
    alert( member + "=" + newObj[member] ); // shows prop1, prop2, prop3
}

JSFIDDLE: http://jsfiddle.net/egret230/efGgT/

1
  • 1
    @BrandtSolovij: Functions are objects: try running (function() {}) instanceof Object Commented May 23, 2012 at 23:35

3 Answers 3

24

Because JSON cannot store functions. According to the spec, a value must be one of:

Valid JSON values
(source: json.org)


As a side note, this code will make the functions noticed by JSON.stringify:

Function.prototype.toJSON = function() { return "Unstorable function" }
Sign up to request clarification or add additional context in comments.

7 Comments

So in this case, JSON can't store undefined?
@Derek: Correct. I think JSON.stringify converts it to null
@Derek: JSON.stringify omits members with undefined values. A variable set to undefined is indistinguishable from one that was never set at all.
@apsillers: ...at least from JSON view. Setting a property to undefined will create the property.
Function.prototype.toJSON Nice one!
|
7

Here is another way with using a .prototype. You can add an function to stringify

JSON.stringify(obj, function(k, v) {
  if (typeof v === 'function') {
    return v + '';
  }
  return v;
});

Comments

2

It's not supposed to stringify methods (or any functions) - especially since most methods of built in objects (and thus the prototypes of any user-defined objects) are native code.

If you really need it to print your methods out, you can override your object's .toString method, but when you call JSON.parse on the stringified output, it will treat the method as if it were just a string, and to be able to call it as a function you'd have to eval it - a practice that is typically not recommended.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.