Google Visualization API将电子表格数据加载为类似CSV的JSON

时间:2017-10-02 22:07:19

标签: json csv google-visualization

我尝试以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
 }]

知道怎么做吗?非常感谢您的帮助。非常感谢!

1 个答案:

答案 0 :(得分:0)

使用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));