javascript - Jquery : Automatic type conversion during parse JSON -



there way specify type while parsing json, conversion happens automatically.

so have jsondata, , x , y values needs number. so, way can think looping , converting each. better logic, or efficient way?

var jsondata = '[{"x:"1", "y":"2"}, {"x:"3", "y":"4"}]' var needed = [{x:1, y:2}, {x:3, y:4}] var vals = $.parsejson(jsondata); // var coord = function(x, y){ this.x = x; this.y = y; } var result = []; function convert(vals) { (var i=0,l=vals.length; i<l; i++) {         var d = vals[i];         result.push(new coord(number(d.x), number(d.y)));     }; }    

the json in jsondata variable not valid. attribute should inside of double quotes. whenever convert data json, use parser (explained on json.org) , don't write hand. can check if json valid using tools jsonlint.

any number (integers, decimal, float) valid json data types , doesn't have encapsulated double quotes.

this valid json: [{"x": 1, "y": 2}, {"x": 3, "y": 4}]

however, if don't have control on source , retrieve json ajax can provide callback function datafilter option. if you're using jquery 1.5 there's converters generalized datafilter callbacks.

i suspect x , y coords decimal number why chose use parsefloat instead of parseint in examples below.

example using datafilter callback function (pre jquery 1.5):

$.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 have x , y float numbers     } }); 

example using converter (jquery 1.5 or later):

$.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 have x , y float numbers }); 

Comments