Is there a way to specify type while parsing Json, so that the conversion happens automatically.
So I have the jsonData, and the x and y values needs to be number. So, the only way I can think about is looping and converting each. Any 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) {
for (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 the jsonData variable is not valid. Only the attribute should be inside of the double quotes. Whenever you convert data to JSON, use a parser (explained on json.org) and don't write it by hand. You can always check if JSON is valid by using tools like JSONLint.
Any number (integers, decimal, float) are valid JSON data types and doesn't have to be encapsulated with double quotes.
This is valid JSON: [{"x": 1, "y": 2}, {"x": 3, "y": 4}]
However, if you don't have control over the source and retrieve the JSON with ajax you can provide a callback function to the dataFilter option. If you're using jQuery 1.5 there's also converters which are generalized dataFilter callbacks.
I suspect that the x and y coords could be a decimal number which is why I chose to use parseFloat instead of parseInt in the examples below.
Example using a 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 now have x and y as float numbers
}
});
Example using a 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 now have x and y as float numbers
});
The only way is to loop through you JSON data and convert the strings you find into numbers using parseInt("2");.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With