Join the Stack Overflow Community
Stack Overflow is a community of 6.5 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

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
up vote 17 down vote accepted

As Jani said, this is not possible directly with JSON, but this might help you: https://waybackassets.bk21.net/20080828165256/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
    
Eval=Evil just that you know – user4433485 Mar 19 '15 at 9: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

json_decode parse the given array to json string, so you can play with it as a string. Just use some unique string to indicate the start and the end of the function. Then use str_replace to remove the quotes.

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

$json = array(   
  'message' => $message,
  'func' => $function
);
$string = json_encode($json);
$string = str_replace('"#!!','',$string);
$string = str_replace('!!#"','',$string);
echo $string;

The output will be:

{"message":"Hello","func":function(){}}
share|improve this answer
    
A small variant to be able to use characters: preg_match_all('/\#([^\#]*)\#/', json_encode($json), $unescape); foreach ($unescape['0'] as $key => $fn) { $string = str_replace($fn, json_decode($unescape['0'][$key]), $string); } – Allartk Jun 9 '16 at 10:10

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

You can try this:

var json_string = '{"message":"Hello","myfunc":"function(){ alert(this.message) }"}';
var json_string = JSON.parse(json_string, function(k,v){
    if(typeof v == 'string' && /function\(\)\{/.test(v)){
        return eval(k+' = '+v); 
    }else{
        return v
    }
});
share|improve this answer

The enconding part in PHP is seems to be solved by now. You can use

json_encode($p, JSON_UNESCAPED_UNICODE)

this way your function will not be escaped. However

share|improve this answer
    
I don't think this does what you think it does. This is to not escape unicode characters which has nothing to do with functions. – cpburnz Feb 17 '16 at 21:01

This function can also help:

function jsonify($var){
return str_ireplace(array("'function",'"function',"}'",'}"'),array("function",'function',"}",'}'),json_encode($var));
}

Taken from here: http://network.convergenceservices.in/forum/105-uknowva-development/4710-introducing-convhelperjsonify-in-uknowva-251.html#4710

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.