Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I need to encode a javascript function into a JSON object in PHP.

This:

$function = "function(){}";
$message = "Hello";

$json = array(   
      'message' => $message,
      'func' => $function
);
echo json_encode($json);

outputs:

{"message":"Hello","func":"function(){}"}

What I want is:

{"message":"Hello","func":function(){}}

Can I do this with json_encode?

share|improve this question

6 Answers 6

up vote 10 down vote accepted

As Jani said, this is not possible directly with JSON, but this might help you : http://solutoire.com/2008/06/12/sending-javascript-functions-over-json/

share|improve this answer
1  
That works, although it's not really JSON anymore. –  Matthew Crumley Nov 17 '09 at 3:12
    
It is a valid JavaScript/Jscript/ECMAScript object, right? –  David Murdoch Nov 17 '09 at 18:26
    
Yes, as long as you parse it with eval instead of using a strict JSON parser. –  Matthew Crumley Nov 18 '09 at 2:53

No. JSON spec does not support functions. You can write your own code to output it in a JSON-like format and it should work fine though.

share|improve this answer

If don't want to write your own JSON encoder you can resort to Zend_Json, the JSON encoder for the Zend Framework. It includes the capability to cope with JSON expressions.

share|improve this answer
1  
Good Lord, this is awesome. –  Stephen J. Fuhry Dec 3 '09 at 19:15

The following is not exactly what you are looking for but may help :

jQuery.ajax({
    url: url,
    type: "POST",
    dataType: "json",
    data: ({
        method: 'mypage' + target,
        prop: value,

    }),
    beforeSend: function() {

    },
    success: function(data) {

        //To change the value of a property in your json object just do this : 
        // ps : data contain a json object (json_decode() in php for example) 

        data.table.draw_data.formatter = function() {return this.y;}

        my_fct(data); // now 'formatter' contains my function :)

    },
    error: function(jqXHR, textStatus, errorThrown) {
        console.log(JSON.stringify(jqXHR));
        console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
    }
});

Hope it helps :)

share|improve this answer

I can't answer my own question because it is a duplicate of this one so here goes:

Below is my basic solution to this problem. Simply prepend 'function:' to a string for the string to not be wrapped in quotes. Feel free to amend as you wish!

From this array:

Picture of my Array

I got this result:

{"showPreviewOnForm":1,"onclose":plform.updateViewports,"uploadScript":"/lib/ajaxstream/upload.php","uploadTo":"temp","more":{"elem":1,"btdev":2,"0":"cdc","BBC":["name","orange",3,5]}}

As you can see, it works!

/**
 * Stringify an array into something that JavaScript understands. Typing 'function:' before a string causes that string to not
 *  be encased in quotes, meaning that JS can understand that it is a function
 * @param array $input The array to turn into a JS object
 * @return string A JSON-like string
 */
function json_stringify($input) {
    $outtext = '';
    $opening = '{';
    $closing = '}';
    $inner = array();
    $numericarray = array_keys($input) === range(0, count($input) - 1);
    if ($numericarray) {
        // This is a numerically sequential array
        $opening = '[';
        $closing = ']';
    } 
    foreach ($input as $key => $val) {
        if (is_string($val) && preg_match("/^function\:/", $val)) {
            // The value is a string and begins with 'function:'. Do not encase it in quotes
            $val = substr($val, 9);
        } else if (is_int($val)) {
            // The value is an integer
            $val = (int) $val;
        } else if (is_float($val)) {
            // The value is a float
            $val = (float) $val;
        } else if (!is_bool($val)) {
            // Keep booleans as they are, and for everything else, come here
            $val = is_array($val) ? self::json_stringify($val) : "\"$val\"";
        }
        $inner[] = ($numericarray ? '' : "\"$key\":") . $val;
    }
    $outtext .= implode(',',$inner);
    return "$opening$outtext$closing";
}

Note: One should only use this function if you need the string to be interpreted as an object straight away. It should not be used if you intend to use JSON.parse with it

share|improve this answer

you cannot do it with json_encode but u can do it afterwards in javascript

json = {"message":"Hello","func":"function(){ alert(this.message) }"}

javascript:

eval('json.func = '+json.func);

call:

json.func();
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.