I have a JSON string that reads:
[{
\"id\": \"id2\",
\"index\": \"2\",
\"str\": \"str2\",
\"cent\": \"200\",
\"triplet\": \"222\"
},
{
Something like this (where objects
is an Array of objects):
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));
The last line will print out this:
[
{
"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
}
]
Try this. I haven't tested it but should 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(parseInt(v))){
jsonForChart[key][k] = parseInt(v);
}else{
jsonForChart[key][k] = v;
}
});
});
You don't need to check if the value is a number:
var temp = [{
"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"
}];
var jsonForChart = jQuery.extend(true, {}, temp);
$.each(temp, function(key, value) {
$.each(value, function(k, v) {
// if the value can be parsed to int, it will be OR the value remains untouched
jsonForChart[key][k] = +v || jsonForChart[key][k];
});
});
document.write("<pre>" + JSON.stringify(jsonForChart, null, 3) + "</pre>");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You get one big object but it's what you expect seeing the line var jsonForChart = jQuery.extend(true, {}, temp);
.
Try this
// Iterate thorugh the array
[].forEach.call(x, function(inst, i){
// Iterate through all the keys
[].forEach.call(Object.keys(inst), function(y){
// Check if string is Numerical string
if(!isNaN(x[i][y]))
//Convert to numerical value
x[i][y] = +x[i][y];
});
});
console.log(x);
Live FIddle