Creating a JSON object from Google Sheets

前端 未结 2 1744
傲寒
傲寒 2020-12-16 02:39

I am trying to learn AppScript and I am using Google Sheets as an example. I want to create a simple JSON object using some data populated in the Sheet.

Table Exampl

2条回答
  •  清歌不尽
    2020-12-16 03:15

    Please try:

    function getJsonArrayFromData(data)
    {
    
      var obj = {};
      var result = [];
      var headers = data[0];
      var cols = headers.length;
      var row = [];
    
      for (var i = 1, l = data.length; i < l; i++)
      {
        // get a row to fill the object
        row = data[i];
        // clear object
        obj = {};
        for (var col = 0; col < cols; col++) 
        {
          // fill object with new values
          obj[headers[col]] = row[col];    
        }
        // add object in a final result
        result.push(obj);  
      }
    
      return result;  
    
    }
    

    Test function:

    function test_getJsonArrayFromData()
    {
      var data =   
        [
          ['Planet', 'Mainland', 'Country', 'City'],
          ['Earth', 'Europe', 'Britain', 'London'],
          ['Earth', 'Europe', 'Britain', 'Manchester'],
          ['Earth', 'Europe', 'Britain', 'Liverpool'],
          ['Earth', 'Europe', 'France', 'Paris'],
          ['Earth', 'Europe', 'France', 'Lion']
        ];
    
        Logger.log(getJsonArrayFromData(data));
    
        // =>  [{Mainland=Europe, Country=Britain, Planet=Earth, City=London}, {Mainland=Europe, Country=Britain, Planet=Earth, City=Manchester}, {Mainland=Europe, Country=Britain, Planet=Earth, City=Liverpool}, {Mainland=Europe, Country=France, Planet=Earth, City=Paris}, {Mainland=Europe, Country=France, Planet=Earth, City=Lion}]
    
    }
    

提交回复
热议问题