Is it possible to add a Function to a json?

Asked

Viewed 146 times

3

Let’s get to the problem. In datatable.js, to display the columns I define as follows:

    "aoColumns": [
                { "mDataProp": "IdProcesso", "sTitle": "Numero" }
                 ]

If you need to perform some function:

                 {
                    "mDataProp": "DataAbertura", "sTitle": "Data Abertura",
                    "fnRender": function (oObj) {
                        return //minha function vem aqui!
                    }
                },

Now comes the question is it possible to add this Function in the Json object dynamically? When I say dynamic I mean the fact that this object will be created by another Function and at the end it returns me a string generated by JSON.stringify and Function is rendered unusable. I hope I’ve been able to explain my doubt

  • 2

    In a json not but an object yes, whether the datatable uses it or not is another question :) This object will be serialized in json or is to be consumed by the datatable API?

  • The application already receives a json I wanted to add the function. Then way will be to create the object and add the necessary function. Okay, thanks so much for the help.

  • This object will be serialized in json or is to be consumed by the datatable API?

  • Consumed by the API.

  • 1

    @Deividsonoliveira, I don’t know if it’s still relevant... but you can pass your Function as a string and when creating the object actually build it using the Function() class. However, this is far from good practice...

1 answer

1


There is an alternative, using the function eval

The function eval executes the string passed to her, as you can see in the example below:

https://jsfiddle.net/yrzruztw/

eval('alert("teste")');

This will make Alert appear on the screen. Therefore my suggestion is that you save your function in the format of string, and execute it so.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.