开发者

Jquery : Automatic type conversion during parse JSON

Is there a way to specify type while parsing Json, so that the conversion happens automatically.

So I hav开发者_如何学Pythone 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");.


I had the same problem. In one line of code, I remove any quotes that are immediately before or after a numeral, or before a minus sign.

var chartData = $.parseJSON(rawData.replace(/"(-?\d)/g, "$1").replace(/(\d)"/g, "$1"));

In my case it was coming via AJAX from PHP code which I have control over, and I later found out I could simply use the JSON_NUMERIC_CHECK - see PHP json_encode encoding numbers as strings.

These solutions convert anything that looks like a number to a number. So if you can have something that looks like a number but needs to be treated as a string, you will need to go and figure out something else, depending on your data.


If you have control of the json source you can remove the quotes from the coordinates.

Acording to json.org, a value can be a sting, number, object, array, true, false, or null. A string is identified as a sequence of characters inclosed in douple quotes. A numeric value not contained in quotes should be interpeted as a number. You might to verify with the parser engine that is in use.

If your just consuming the json, the datafilter and converter methods, mention already, would be the most jquery way to solve the task.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜