How to replace string values ​​with numeric values ​​inside json object used in google visualization api chart diagram

I have a Json string that I use to render a google chart, which should be in this exact format, and I need to replace each value with "v", which is a number, its numeric value (value without ""), I have to do some javascript replacement function, but I could not find a way to move the json object. Here is an example json string I have to change:

{"cols":[
{"id":"r","label":"Reason","type":"string"},
{"id":"m","label":"Minutes","type":"number"}
],
"rows":[
{"c":[
     {"v":"Flour - Blower","f":"Flour - Blower"},
     {"v":"7","f":"7"}]},
{"c":[
     {"v":"Whole Line - d","f":"Whole Line - d"},
     {"v":"4","f":"4"}]},
{"c":[
     {"v":"Flour - Pipework","f":"Flour - Pipework"},
     {"v":"3","f":"3"}]},
{"c":[
     {"v":"Horseshoe - Belt","f":"Horseshoe - Belt"},
     {"v":"1","f":"1"}]}
],
"p":null
}

Maybe I should do something like:

var jsonStr = ...;

for (i in jsonStr.rows) {
   for(j in jsonStr[i].c)
   { 
    if (parseInt(jsonStr[i].c[j].v) != 'NaN') {
        jsonStr.rows[i].c[j].v = parseInt(jsonStr.rows[i].c[j].v);
   }
 }
+4
source share
3 answers

JSON , string.replace:

jsonStr = JSON.stringify(jsonStr);
jsonStr = jsonStr.replace(/"v":"(\d+)"/g, '"v":$1');

Jsfiddle demo

+7

, , , . , , , , - NaN

, NaN === NaN, , false.

, isNaN ( parseInt ). , -

for (i in jsonStr.rows) {
   for(j in jsonStr[i].c)
   { 
    if (!isNaN(jsonStr[i].c[j].v)) {
        jsonStr.rows[i].c[j].v = parseInt(jsonStr.rows[i].c[j].v);
   }
 }
+2

, , isNaN :

function convertNumberToInteger(val) {
    if (isNaN(val)) {
        return val;
    } else {
        return parseInt(val);
    }
}

:

convertNumberToInteger("sasdfasdf");
Output: "sasdfasdf"

convertNumberToInteger("3");
Output: 3

, forEach JSON

+1

All Articles