Jquery : Automatic type conversion during parse JSON

后端 未结 4 761
猫巷女王i
猫巷女王i 2021-01-14 22:58


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 n

4条回答
  •  清酒与你
    2021-01-14 23:45

    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
    });
    

提交回复
热议问题