Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You're going to have to use the <code>eval()</code> (<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/eval" rel="noreferrer">doc</a>) function. A lot of people have a lot of feelings about this function. JSON is best for transporting data, not functions (see <a href="https://developer.mozilla.org/en/JSON" rel="noreferrer">JSON</a>). The functions ought to lay in the script on the page. Also there's a syntax error in your posted code (function is wrapped in single quotes ('), and so is console.log's first parameter). But...</p> <pre><code>json = "{\"run\":\"function() { console.log('running...'); }\"}"; //Fixed, thanks obj = JSON.parse(json); eval(obj.run); //Logs "running..." </code></pre> <hr> <p><strong>Update:</strong></p> <p>Oh, and I was mistaken. Eval doesn't seem to like anonymous functions. With the revised code, it will parse json into an object with a run property that is a <code>String</code>, with value <code>"function() { console.log('running...'); }"</code>. But when you <code>eval(obj.run);</code>, you will get a SyntaxError declaring an unexpected (. Presumably, this is the ( in function <strong>(</strong>).</p> <p>So, I can think of two ways of dealing with this:</p> <ol> <li>Remove the anonymous function in your actual JSON string (so, make your PHP forget about <code>function () {</code>), and eval it. This means it will be called as soon as you <code>eval</code> it.</li> <li><p>What I think you want, is to be able to evaluate it to an anonymous function, that will be called when you want. So, you could write a wrapper function (you would need to follow option 1 for this as well):</p> <pre><code>function returnEval(str) { return function () { eval(str); } } </code></pre> <p>This would allow you to call it. So:</p> <pre><code>obj = JSON.parse(json); obj.run = returnEval(obj.run); obj.run(); //Logs "running..." </code></pre></li> </ol> <p>Hope this helps!</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload