JSON数据从类表格式转换为JSON

JSON data transformation from table-like format to JSON?

本文关键字:JSON 转换 格式 数据 表格      更新时间:2023-09-26

我有以下格式的数据:

{
  "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循环深入研究之前,我想知道是否有一种超快速的方法来转换它。我对使用Undercore这样的库持开放态度。

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

演示

没有简单的方法,而且这实际上并不是一个复杂的操作,即使使用for循环也是如此。我不知道你为什么要用regex来做这件事。

我会从将列值读入一个数字索引数组开始。

所以类似于:

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

这应该对你有用。