将json字符串值转换为数字 [英] Convert json string value to number
本文介绍了将json字符串值转换为数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个JSON字符串,内容如下:
I have a JSON string that reads:
[{
"id": "id2",
"index": "2",
"str": "str2",
"cent": "200",
"triplet": "222"
},
{
"id": "id3",
"index": "3",
"str": "str3",
"cent": "300",
"triplet": "333"
},
{
"id": "id4",
"index": "4",
"str": "str4",
"cent": "400",
"triplet": "444"
},
{
"id": "id5",
"index": "5",
"str": "str5",
"cent": "500",
"triplet": "555"
}]
键值对来自动态来自服务器,我事先不知道预期的数据。
对于我使用的图表库,我需要JSON中的值是数字而不是字符串viz。 index:2
而不是index:2
我需要这样做使用纯JS或jQuery操作客户端。
The key-value pairs come dynamically from the server and I won't know beforehand what data to expect.
For a charting library that I use, I need the values in JSON to be numeric rather than string viz. "index":2
instead of "index":"2"
I am required to do this manipulation client-side using pure JS or jQuery.
这是我的方法,但它似乎不起作用:
This was my approach but it doesn't seem to work:
var temp = //some json that I receive
var jsonForChart = jQuery.extend(true, {}, temp);
$.each(temp, function(key, value) {
$.each(value, function(k, v) {
if(!isNaN(v)){
jsonForChart[key][k] = Number(v);
}
});
});
推荐答案
像这个(其中对象
是一个对象数组):
Something like this (where objects
is an Array of objects):
JavaScript
JavaScript
for(var i = 0; i < objects.length; i++){
var obj = objects[i];
for(var prop in obj){
if(obj.hasOwnProperty(prop) && obj[prop] !== null && !isNaN(obj[prop])){
obj[prop] = +obj[prop];
}
}
}
console.log(JSON.stringify(objects, null, 2));
最后一行将打印出来:
[
{
"id": "id2",
"index": 2,
"str": "str2",
"cent": 200,
"triplet": 222
},
{
"id": "id3",
"index": 3,
"str": "str3",
"cent": 300,
"triplet": 333
},
{
"id": "id4",
"index": 4,
"str": "str4",
"cent": 400,
"triplet": 444
},
{
"id": "id5",
"index": 5,
"str": "str5",
"cent": 500,
"triplet": 555
}
]
这篇关于将json字符串值转换为数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文