本文介绍了jQuery:解析JSON时自动进行类型转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


解析Json时是否可以指定类型,以便自动进行转换.


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

所以我有jsonData,并且x和y值需要为数字.因此,我唯一能想到的方法就是循环和转换每个.还有更好的逻辑或有效的方法吗?

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

推荐答案

jsonData变量中的JSON无效.只有属性应该在双引号内.每当将数据转换为JSON时,请使用解析器(在json.org上解释),并且不要编写它用手.您始终可以使用 JSONLint 之类的工具来检查JSON是否有效.

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.

任何数字(整数,十进制,浮点数)都是有效的JSON数据类型,不必用双引号引起来.

Any number (integers, decimal, float) are valid JSON data types and doesn't have to be encapsulated with double quotes.

这是有效的JSON:[{"x": 1, "y": 2}, {"x": 3, "y": 4}]

This is valid JSON: [{"x": 1, "y": 2}, {"x": 3, "y": 4}]

但是,如果您无法控制源并使用ajax检索JSON,则可以向 dataFilter 选项.如果您使用的是jQuery 1.5,那么 converters 也会被概括dataFilter回调.

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.

我怀疑x和y坐标可能是十进制数,这就是为什么我在以下示例中选择使用parseFloat而不是parseInt的原因.

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.

使用dataFilter回调函数(jQuery 1.5之前的版本)的示例:

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

使用converter(jQuery 1.5或更高版本)的示例:

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

这篇关于jQuery:解析JSON时自动进行类型转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-12 08:45