Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>All JSON is valid javascript (not always the other way around, though).</p> <pre><code>// These two lines are equivalent var someObject = { a: 'a', b: 'b' }; var someObject = jQuery.parseJSON('{ "a": "a", "b": "b" }'); </code></pre> <p>If you are getting your JSON string from a request to an external resource, I think what you are currently doing is the best way to do it. You <em>could</em> insert the JSON into a new <code>script</code> element, if you really wanted, like so:</p> <pre><code>var $body = $(document.body); $body.append("&lt;script type='text/javascript'&gt;var myJsonObject = " + jsonString + ";&lt;/script&gt;"); </code></pre> <p>I personally don't think this looks cleaner, but there are some other problems with this approach. If a hacker was able to put his/her own javascript into some JSON response your site was getting back, that harmful javascript would run on your site, potentially wreaking havoc on your site and embarrassing you. (You shouldn't use <code>eval(jsonString)</code> for the same reason.)</p> <p>Secondly, the javascript would create a global variable (at least in this case) and would not be executed in the same scope as the currently running function.</p> <p>Not to mention the unnecessary expense of creating a new <code>script</code> element and inserting it into the DOM every time you want to parse some JSON.</p> <p>The way you are doing it now is great because 1) if there is harmful javascript in your JSON string, it will cause a parse error (JSON only holds data, and can't execute commands) and 2) it keeps everything in the current scope.</p>
    singulars
    1. This table or related slice is empty.
    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.
 

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