javascript Jquery:解析 JSON 期间的自动类型转换
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5834901/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Jquery : Automatic type conversion during parse JSON
提问by bsr
Is there a way to specify type while parsing Json, so that the conversion happens automatically.
有没有办法在解析 Json 时指定类型,以便自动进行转换。
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?
所以我有 jsonData,x 和 y 值需要是数字。所以,我能想到的唯一方法是循环和转换每个。任何更好的逻辑或有效的方法?
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)));
};
}
回答by mekwall
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.
jsonData
变量中的 JSON无效。只有属性应该在双引号内。每当您将数据转换为 JSON 时,请使用解析器(在 json.org 上进行了解释)并且不要手动编写。您始终可以使用JSONLint 之类的工具检查 JSON 是否有效。
Any number (integers, decimal, float) are valid JSON data types and doesn't have to be encapsulated with double quotes.
任何数字(整数、小数、浮点数)都是有效的 JSON 数据类型,不必用双引号封装。
This is valid JSON: [{"x": 1, "y": 2}, {"x": 3, "y": 4}]
这是有效的 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.
但是,如果您无法控制源并使用 ajax 检索 JSON,则可以为该dataFilter
选项提供回调函数。如果您使用的是 jQuery 1.5,那么还有converters
哪些是通用的 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.
我怀疑 x 和 y 坐标可能是一个十进制数,这就是为什么我选择使用parseFloat
而不是parseInt
在下面的示例中。
Example using a dataFilter
callback function (pre jQuery 1.5):
使用dataFilter
回调函数的示例(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):
使用converter
(jQuery 1.5 或更高版本)的示例:
$.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
});
回答by Luca Matteis
The only way is to loop through you JSON data and convert the strings you find into numbers using parseInt("2");
.
唯一的方法是遍历您的 JSON 数据并使用parseInt("2");
.
回答by Peter Smartt
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, "").replace(/(\d)"/g, ""));
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.
在我的情况下,它是通过 AJAX 来自我可以控制的 PHP 代码,后来我发现我可以简单地使用 JSON_NUMERIC_CHECK - 将PHP json_encode 编码数字视为字符串。
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.
这些解决方案将任何看起来像数字的东西转换为数字。因此,如果您可以拥有一些看起来像数字但需要被视为字符串的东西,您将需要根据您的数据找出其他东西。
回答by Robert Beuligmann
If you have control of the json source you can remove the quotes from the coordinates.
如果您可以控制 json 源,则可以从坐标中删除引号。
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.
根据 json.org,值可以是字符串、数字、对象、数组、true、false 或 null。字符串被标识为包含在双引号中的字符序列。未包含在引号中的数值应作为数字进行解释。您可能会使用正在使用的解析器引擎进行验证。
If your just consuming the json, the datafilter and converter methods, mention already, would be the most jquery way to solve the task.
如果您只是使用 json,那么已经提到的 datafilter 和转换器方法将是解决该任务的最 jquery 方法。