views:

30

answers:

1

I have a json object with a function:

var thread = {
    title: "my title",
    delete: function() {
        alert("deleted");
    }
};

thread.delete(); // alerted "deleted"

thread_json = JSON.encode(thread); // convert to json from object

thread_object = JSON.decode(thread_json); // convert to object from json

thread_object.delete(); // this didn't work

After I converted it back from json string to object, I could not use delete() function.

When you convert something to json, the functions are gone?

Are there ways to keep them in the json string?

I'm using Mootools.

+2  A: 

You got it. Take a look at that JSON.encode output. Only simple data types are allowed in JSON representations, partly for ease of creation, and partly for security. (The reason we use something like JSON.decode instead of eval is the possibility of embedding functions.)

You'll have to modify the JSON library source code to accept functions, or write your own in order to preserve the literal definition of the object upon conversion to string.

Consider, though, the possibility that you don't really need to do this. There's probably a better solution, but I can't begin to address that without knowing your exact situation.

Matchu
Also, once your encoding functions in your serialized string then by definition it is no longer a JSON string (to be more accurate, it is an invalid JSON string).
slebetman