当前位置: 代码迷 >> JavaScript >> JSON数据从表格格式转换为JSON吗?
  详细解决方案

JSON数据从表格格式转换为JSON吗?

热度:90   发布时间:2023-06-13 11:42:52.0

我有以下格式的数据:

{
  "columns": [
    {
      "values": [
        {
          "data": [
            "Project Name",
            "Owner",
            "Creation Date",
            "Completed Tasks"
          ]
        }
      ]
    }
  ],
  "rows": [
    {
      "values": [
        {
          "data": [
            "My Project 1",
            "Franklin",
            "7/1/2015",
            "387"
          ]
        }
      ]
    },
    {
      "values": [
        {
          "data": [
            "My Project 2",
            "Beth",
            "7/12/2015",
            "402"
          ]
        }
      ]
    }
  ]
}

有什么超级短/简单的方法可以像这样格式化它:

{
  "projects": [
    {
      "projectName": "My Project 1",
      "owner": "Franklin",
      "creationDate": "7/1/2015",
      "completedTasks": "387"
    },
    {
      "projectName": "My Project 2",
      "owner": "Beth",
      "creationDate": "7/12/2015",
      "completedTasks": "402"
    }
  ]
}

我已经有了列名翻译代码:

r = s.replace(/\%/g, 'Perc')
.replace(/^[0-9A-Z]/g, function (x) {
  return x.toLowerCase();
}).replace(/[\(\)\s]/g, '');

在通过一堆forEach循环深入探讨此问题之前,我想知道是否存在一种超级快速的方法来进行转换。 我愿意使用Underscore之类的库。

没有简单的方法,即使使用for循环,这实际上也没有那么复杂。 我不知道您为什么要使用正则表达式来执行此操作。

我将从将列值读出到数字索引数组开始。

所以像这样:

var sourceData = JSON.parse(yourJSONstring);
var columns = sourceData.columns[0].values[0].data;

现在,您有了一种方便的方法来开始构建所需的对象。 您可以使用上面创建的columns数组在最终对象中提供属性键标签。

var sourceRows = sourceData.rows;
var finalData = {
    "projects": []
};
// iterate through rows and write to object
for (i = 0; i < sourceRows.length; i++) {
    var sourceRow = sourceRows[i].values.data;
    // load data from row in finalData object
    for (j = 0; j < sourceRow.length; j++) {
        finalData.projects[i][columns[j]] = sourceRow[j];
    }
}

那应该为您解决问题。

function translate(str) {
    return str.replace(/\%/g, 'Perc')
        .replace(/^[0-9A-Z]/g, function (x) {
            return x.toLowerCase();
        })
        .replace(/[\(\)\s]/g, '');
}

function newFormat(obj) {

    // grab the column names
    var colNames = obj.columns[0].values[0].data;

    // create a new temporary array
    var out = [];
    var rows = obj.rows;

    // loop over the rows
    rows.forEach(function (row) {
        var record = row.values[0].data;

        // create a new object, loop over the existing array elements
        // and add them to the object using the column names as keys
        var newRec = {};
        for (var i = 0, l = record.length; i < l; i++) {
            newRec[translate(colNames[i])] = record[i];
        }

        // push the new object to the array
        out.push(newRec);
    });

    // return the final object
    return { projects: out };
}

  相关解决方案