Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The JSON in the <code>jsonData</code> variable is not valid. Only the attribute should be inside of the double quotes. Whenever you convert data to JSON, use a parser (<a href="http://json.org/js.html" rel="noreferrer">explained on json.org</a>) and don't write it by hand. You can always check if JSON is valid by using tools like <a href="http://jsonlint.com/" rel="noreferrer">JSONLint</a>.</p> <p>Any number (integers, decimal, float) are valid JSON data types and doesn't have to be encapsulated with double quotes.</p> <p>This is valid JSON: <code>[{"x": 1, "y": 2}, {"x": 3, "y": 4}]</code></p> <p>However, if you don't have control over the source and retrieve the JSON with ajax you can provide a callback function to the <a href="http://api.jquery.com/jQuery.ajax" rel="noreferrer"><code>dataFilter</code></a> option. If you're using jQuery 1.5 there's also <a href="http://api.jquery.com/extending-ajax/#Converters" rel="noreferrer"><code>converters</code></a> which are <em>generalized dataFilter callbacks</em>.</p> <p>I suspect that the x and y coords could be a decimal number which is why I chose to use <code>parseFloat</code> instead of <code>parseInt</code> in the examples below.</p> <p>Example using a <code>dataFilter</code> callback function (pre jQuery 1.5):</p> <pre><code>$.ajax({ url: "/foo/", dataFilter: function(data, type){ if (type == "json") { var json = $.parseJSON(data); $.each(json, function(i,o){ if (o.x) { json[i].x = parseFloat(o.x); } if (o.y) { json[i].y = parseFloat(o.y); } }); } return data; }, success: function(data){ // data should now have x and y as float numbers } }); </code></pre> <p>Example using a <code>converter</code> (jQuery 1.5 or later):</p> <pre><code>$.ajaxSetup({ converters: { "json jsoncoords": function(data) { if (valid(data)) { $.each(data, function(i,o){ if (o.x) { data[i].x = parseFloat(o.x); } if (o.y) { data[i].y = parseFloat(o.y); } }); return data; } else { throw exceptionObject; } } } }); $.ajax({ url: "/foo/", dataType: "jsoncoords" }).success(function(data){ // data should now have x and y as float numbers }); </code></pre>
 

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