Google可视化API加载电子表格数据类似于CSV样JSON



我尝试以JSON格式从Google电子表格中加载数据。作为回应,我会收到JSON,例如...

{
  cols: [{id: 'A', label: 'column_A', type: 'string'},
         {id: 'B', label: 'column_B', type: 'string'},
         {id: 'C', label: 'column_C', type: 'string'}
  ],
  rows: [{c:[{v: '1'},
             {v: '2'},
             {v: '3'}
        ]},
         {c:[{v: 'a'},
             {v: 'b'},
             {v: 'c'}
        ]},
         {c:[{v: '1'},
             {v: '2'},
             {v: '3'}
        ]}
  ]
}

...但是我需要的是一个JSON,例如CSV转换为JSON

[{'column_A': 1,
  'column_B': 2,
  'column_C': 3
 },
 {'column_A': 'a',
  'column_B': 'b',
  'column_C': 'c'
 },
 {'column_A': 1,
  'column_B': 2,
  'column_C': 3
 }]

任何想法如何做?非常感谢您的帮助。非常感谢!

使用map方法转换rows数组
使用cols数组来命名每行

请参阅以下工作片段...

var jsonGoogle = {
  cols: [
    {id: 'A', label: 'column_A', type: 'string'},
    {id: 'B', label: 'column_B', type: 'string'},
    {id: 'C', label: 'column_C', type: 'string'}
  ],
  rows: [
    {c:[
      {v: '1'},
      {v: '2'},
      {v: '3'}
    ]},
    {c:[
      {v: 'a'},
      {v: 'b'},
      {v: 'c'}
    ]},
    {c:[
      {v: '1'},
      {v: '2'},
      {v: '3'}
    ]}
  ]
};
var jsonCSV = jsonGoogle.rows.map(function (row) {
  var rowCSV = {};
  jsonGoogle.cols.forEach(function (col, index) {
    rowCSV[col.label] = row.c[index].v;
  });
  return rowCSV;
});
console.log(JSON.stringify(jsonCSV));

最新更新