0

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.

3
  • 1
    That's not a 'json object'. There is no 'json object'. JSON is a text format... text to represent objects. Nope, JSON object representations don't include functions... the best you can do is include the function body as text and create a function via Function after parsing the JSON string. Commented Sep 24, 2010 at 3:28
  • 1
    JSON doesn't preserve functions. Commented Sep 24, 2010 at 3:28
  • 2
    BY definition, JSON (the format) must not preserve functions. Here's the official spec: json.org Commented Sep 24, 2010 at 3:59

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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).

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.