title: Pass a JavaScript function through JSON
body: <p>I have a server side Python script that returns a JSON string containing parameters for a client side JavaScript.</p>
  
  <pre><code># Python
  import simplejson as json
  
  def server_script()
    params = {'formatting_function': 'foobarfun'}
    return json.dumps(params)
  </code></pre>
  
  <p>This <code>foobarfun</code> should refer to a JavaScript function. Here is my main client side script</p>
  
  <pre><code>// JavaScript
  function client_script() {
    var xhr = new XMLHttpRequest();
    xhr.open("GET", url, async=true);
    xhr.onreadystatechange = function() {
      if (xhr.readyState == 4) {
        options = JSON.parse(xhr.responseText);
        options.formatting_function();
      }
    };
    xhr.send(null);
  }
  
  function foobarfun() {
    //do_something_funny_here...
  }
  </code></pre>
  
  <p>Of course, <code>options.formatting_function()</code> will complain that "a string is not callable" or something to that effect.</p>
  
  <p>Upon using Chrome's Inspect Element, under the <strong>Resources</strong> tab, and navigating the left sidebar for <strong>XHR > query</strong>, I find that <code>client_script</code> interprets <code>options</code> as below. <code>foobarfun</code> is seen as a string.</p>
  
  <pre><code>// JavaScript
  options = {"formatting_function": "foobarfun"}
  </code></pre>
  
  <p>I would have liked <code>client_script</code> to see <code>options</code> as</p>
  
  <pre><code>// JavaScript
  options = {"formatting function": foobarfun}
  </code></pre>
  
  <p>Of course, doing the following within Python will have it complaining that it doesn't know anything about <code>foobarfun</code></p>
  
  <pre><code># Python
  params = {'formatting_function': foobarfun}
  </code></pre>
  
  <p><strong>QUESTION:</strong><br>
  How should I prepare my JSON string from the server side so that the client script can interpret it correctly? In this case, I want <code>foobarfun</code> to be interpreted as a function object, not as a string.</p>
  
  <p>Or maybe it's something I should do on the client side?</p>