首页 > 解决方案 > 如何将json数据转换成表格

问题描述

我有以下 api 调用,它以 JSON 格式返回数据:

https://xama-was-service.herokuapp.com/api/socialone/databoards/10042?1=2019-02-01T00:00:00.000Z&2=test

返回数据如下:

[
    [
        {
            "Empid": 2326,
            "Empname": "Sam Smith",
            "AbsenceId": 12840,
            "Comment": "a001t000004FQgHAAW",
            "AbsenceStartDate": "2019-05-31T00:00:00.000Z",
            "AbsenceEndDate": "2019-05-31T00:00:00.000Z",
            "JobId": 400004,
            "AbsenceRequestId": ""
        },
        {
            "Empid": 3387,
            "Empname": "Joe bloggs",
            "AbsenceId": 12842,
            "Comment": "a001t000004FK67AAG",
            "AbsenceStartDate": "2019-06-06T00:00:00.000Z",
            "AbsenceEndDate": "2019-06-10T00:00:00.000Z",
            "JobId": 700004,
            "AbsenceRequestId": ""
       }
    ]
]

我想将其移至 excel 和 power bi 但我无法将其转换为表格?

谁能建议如何将返回的数据格式化为表格或在原始调用中使用什么代码来帮助解决这个问题?

理想的最终产品如下,但不知道如何实现?

在此处输入图像描述

谢谢。

标签: javascriptjsonexcelparsingetl

解决方案


这会将您的数据解析为逗号分隔的字符串 (CSV)。

您只需要用逗号分隔每个行元素,,并用换行符分隔每行\n。Excel 知道这种格式,但有时您可能需要使用 text to columns 函数让它知道数据是逗号分隔的。

const data = [

    [

        {

            "Empid": 2326,

            "Empname": "Sam Smith",

            "AbsenceId": 12840,

            "Comment": "a001t000004FQgHAAW",

            "AbsenceStartDate": "2019-05-31T00:00:00.000Z",

            "AbsenceEndDate": "2019-05-31T00:00:00.000Z",

            "JobId": 400004,

            "AbsenceRequestId": ""

        },

        {

            "Empid": 3387,

            "Empname": "Joe bloggs",

            "AbsenceId": 12842,

            "Comment": "a001t000004FK67AAG",

            "AbsenceStartDate": "2019-06-06T00:00:00.000Z",

            "AbsenceEndDate": "2019-06-10T00:00:00.000Z",

            "JobId": 700004,

            "AbsenceRequestId": ""

       }

    ]

]



window.generateCSV = function () {
  let CSVData = ''
  // set the column names
  for (const value of Object.keys(data[0][0])) {
    CSVData = CSVData.concat(value + ',')
  }
  CSVData = CSVData.slice(0, CSVData.length - 1)
  CSVData = CSVData.concat('\n')
  
  // parse the data
	for (const tbl of data) {
		for (const row of tbl) {
			for (const value of Object.values(row)) {
      	CSVData = CSVData.concat(value + ',')
      }
      CSVData = CSVData.slice(0, CSVData.length - 2)
      CSVData = CSVData.concat('\n')
    }
  }
  document.getElementById("csvdata").innerText = CSVData

}
<input type="button" value="generateCSV" onclick="generateCSV()">

<div id="csvdata">

</div>

通过记事本将输出字符串保存到 .txt 或 .csv 后,我可以在 excel 中打开来获取它。

在此处输入图像描述


推荐阅读