6

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"
}]

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);
        }
    });
});
1
  • what seems to be the problem? Are you getting any errors? Commented Dec 1, 2015 at 6:55

4 Answers 4

12

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
  }
]
Sign up to request clarification or add additional context in comments.

3 Comments

This converts null to 0. I just spent 2 hours on a bug caused by this.
@MickaelBergeronNéron Fixed.
Yeah this works. But Can this go a little deeper. If one of the property is object then this code should even go into that obj and convert values. Kind of recurcively.
2

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

Comments

1

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

1 Comment

Doesn't make much of a difference with that else condition. Thanks for the suggestion though :)
1

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

1 Comment

Works correctly for the conversion; somehow not getting the desired result with the charts.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.