【问题标题】:Converting strings to intergers in JSON using JavaScript使用 JavaScript 将字符串转换为 JSON 中的整数
【发布时间】:2017-02-01 02:48:16
【问题描述】:

我有以下 json

{
  "Title": "Test",
  "StartDate": {
    "Month": "3",
    "Year": "1973"
  },
  "EndDate": {
    "Month": "4",
    "Year": "1974"
  }
}

我希望 StartDateEndDate 中的 MonthYear 值不带引号,如下所示:

{
  "Title": "Test",
  "StartDate": {
    "Month": 3,
    "Year": 1973
  },
  "EndDate": {
    "Month": 4,
    "Year": 1974
  }
}

编辑 我没有使用 JSON.stringify() 创建 json。我的 JSON 是由 Angular 2 的 Form Builder 模块创建的,尽管我将它的类型设置为数字,但在我更改值后,值会得到引号。

【问题讨论】:

  • 数据从何而来?您最好在源代码处正确构建它。否则,您始终可以使用 parseFloat()parseInt()
  • 您是从某个地方获取那个 JSON 吗?还是你自己生成?可以在编码为 JSON 之前解决此问题吗?还是您必须使用此 JSON 并在内部需要将值作为数字?预期包含数字的特定属性是否已知,或者您是否必须评估每个值是否应该是数字? 这不是一个可以回答的问题!
  • @deceze json 是由 FormBuilder 模块从角度 2 生成的

标签: javascript json


【解决方案1】:

我看不到结果的数据顺序,所以这里有两个版本。

对象-> JSON(-> 对象)

这适用于JSON.stringify 以及为某些键创建数字的替换函数,例如 MonthYear

var dataObj = { "Title": "Test", "StartDate": { "Month": "3", "Year": "1973" }, "EndDate": { "Month": "4", "Year": "1974" } },
    jsonStr = JSON.stringify(dataObj, function (k, v) {
        return ['Month', 'Year'].indexOf(k) !== -1 ? +v : v;
    }),
    parsed = JSON.parse(jsonStr);

console.log(jsonStr);
console.log(parsed);

JSON -> 对象

这适用于JSON.parse 以及为某些键创建数字的 reviver 函数,例如 MonthYear

var jsonStr = '{ "Title": "Test", "StartDate": { "Month": "3", "Year": "1973" }, "EndDate": { "Month": "4", "Year": "1974" } }',
    parsed = JSON.parse(jsonStr, function (k, v) {
        return ['Month', 'Year'].indexOf(k) !== -1 ? +v : v;
    });

console.log(parsed);

【讨论】:

    【解决方案2】:

    只需将字符串转换为数字即可。 此代码只是一个示例,您可以根据您的对象结构对其进行调整。

    function normalize(target) {
      for (const date of ['StartDate', 'EndDate']) {
        for (const item of ['Month', 'Year']) {
          target[date][item] = Number(target[date][item]);
        }
      }
    }
    

    【讨论】:

      【解决方案3】:

      编辑

      如果您之前在 JavaScript 代码中创建了该 JSON 对象,请选择 @Adrian Lambertz 的答案。如果您从其他地方获得 JSON 作为字符串并想要转换它,请阅读我的答案:

      我原来的答案

      假设您在 JavaScript 代码中将此 JSON 作为字符串,您可以将所需的值转换为整数,如下所示:

      var events = JSON.parse(JSONStringYouWantToConvert);
      
      // if the JSON String is an array of events that all have a Title, a StartDate and an EndDate
      for (var i = 0; i < events.length; i++) {
          // else, forget about the loop and the [i] index, the concept remains the same
          events[i].StartDate.Month = parseInt(events[i].StartDate.Month);
          events[i].StartDate.Year = parseInt(events[i].StartDate.Year);
          events[i].EndDate.Month = parseInt(events[i].EndDate.Month);
          events[i].EndDate.Year = parseInt(events[i].EndDate.Year);
      }
      
      // make a JSON String that wont have the quotes around the Month and Year numbers
      var JSONStringConverted = JSON.stringify(events);
      

      【讨论】:

        【解决方案4】:

        在保存 JSON 之前,使用 parseInt() 函数将值转换为整数。这将删除引号。

        JSON.stringify({
            Month: parseInt( value , 10);
        })
        

        this answer

        【讨论】:

          猜你喜欢
          • 2023-03-19
          • 1970-01-01
          • 2018-12-17
          • 1970-01-01
          • 1970-01-01
          • 2015-08-01
          • 1970-01-01
          • 1970-01-01
          • 2011-05-09
          相关资源
          最近更新 更多