Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The reason why this question pops up in your mind is because you don't understand neither Javascript or JSON enough.</p> <p>The Javascript array is always the numerical array. There is no associate array in JavaScript like the one you get in PHP using <code>json_decode(json, true);</code>. When people talking about associate array in JavaScript, they are in fact using JavaScript objects and it's properties, i.e.,</p> <pre><code>var my_so_called_array = {}; my_so_called_array['first_item'] = 'hello world'; alert(my_so_called_array['first_item']); // 'hello world' alert(my_so_called_array.first_item); // also 'hello world' </code></pre> <p>One of the best about JSON is that the syntax is a subset of the object literal notation. That means JSON string itself is valid code for representing the "associate array" in Javascript. The "conversion" couldn't be simpler, just <code>eval()</code> the string as code will do:</p> <pre><code>var my_data = eval(json_string); </code></pre> <p>Or, use <code>jQuery.parseJSON()</code> or <code>JSON.parse()</code>:</p> <pre><code>var my_data = jQuery.parseJSON(json_string); var my_data = JSON.parse(json_string); </code></pre> <p>The reason people prefer using <code>jQuery.parseJSON()</code> or <code>JSON.parse()</code> over <code>eval()</code> is because <strong>eval is evil</strong>: </p> <ol> <li>It's slower</li> <li>It doesn't check the validity of the JSON code, makes it suspect-able to injection attack.</li> </ol> <p>Does the above explanation answer your question? You can find more information about JSON at www.json.org.</p>
 

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