js:使用JSON.parse reviver进行自动数字转换

时间:2016-12-07 14:30:22

标签: javascript html

我试图通过正则表达式从引号中删除引号来将引号(字符串)转换为自动类型。 喜欢来自" 123"到123.

我正在使用JSON.parse reviver函数,但似乎无法替换它。

我需要什么:

  1. 在reviver中替换应该工作。见下面的代码
  2. 通用正确的正则表达式,可以处理所有类型的数字。我不确定我是否正在使用正确的正则表达式。
  3. 有没有图书馆已经做过这样的事情?请提及
  4. JSFIDDLE:https://jsfiddle.net/bababalcksheep/j1drseny/

    CODE:

    var test = {
       "int": 123,
       "intString": "123",
       "Scientific_1_String": "5.56789e+0",
       "Scientific_1": 5.56789e+0,
       "Scientific_2_String": "5.56789e-0",
       "Scientific_2": 5.56789e-0,
       "Scientific_3_String": "3.125e7",
       "Scientific_3": 3.125e7,
       "notNumber": "675.805.714",
       "dg": "675-805-714",
       "hex": "675.805.714",
       "trueString": "true",
       "trueBool": true,
       "falseString": "false",
       "falseBool": false,
    
     };
     test = JSON.stringify(test);
     var parsedJson = JSON.parse(test, function(key, value) {
       if (typeof value === 'string') {
         if (value === 'false') {
           return false;
         } else if (value === 'true') {
           return true;
         } else {
           // try to remove quotes from number types
           value = value.replace(/"(-?[\d]+\.?[\d]+)"/g, "$1");
           return value;
         }
       } else {
         return value;
       }
     });
     console.log(parsedJson);
    

2 个答案:

答案 0 :(得分:4)

您可以使用Number()函数将字符串转换为数字。如果字符串不是数字,则此函数将返回NaN

此代码应该有效:



const test = JSON.stringify({
  "int": 123,
  "intString": "123",
  "Scientific_1_String": "5.56789e+0",
  "Scientific_1": 5.56789e+0,
  "Scientific_2_String": "5.56789e-0",
  "Scientific_2": 5.56789e-0,
  "Scientific_3_String": "3.125e7",
  "Scientific_3": 3.125e7,
  "notNumber": "675.805.714",
  "dg": "675-805-714",
  "hex": "675.805.714",
  "trueString": "true",
  "trueBool": true,
  "falseString": "false",
  "falseBool": false,
});

const parsed = JSON.parse(test, (key, value) => {
  if (typeof value === 'string') {
    const valueNumber = Number(value);
    if (!Number.isNaN(valueNumber)) {
      return valueNumber;
    }
  }
  return value;
});

console.log(parsed);




答案 1 :(得分:0)

为什么要对它进行字符串化然后处理它,当它在JSON对象上更容易实现时,例如:

var fixedTest = Object.keys(test).reduce((fixedObj, field) => {
  fixedObj[field] = isNaN(test[field]) ? test[field] : +test[field];
  return fixedObj;
}, {});