google-apps-scriptgoogle-sheetssetvalue

Cannot Set Value of JSON Data to Separate Cells


I wrote up the following script, which pulls all the data in just fine. But when I try to break it up into different cells, it returns nothing. What am I missing here?

function myMonitor() {
//GET KEY

var sh=SpreadsheetApp.getActiveSpreadsheet().getSheetByName(“NINFO”);
**var rowNum = sh.getRange(‘F6’).getValue(); **

//POST CALL

** var url = “http://monitor.incognito.org/pubkeystat/stat”; **
** var data = { “mpk”: rowNum**
** };**

** var options = {**
** ‘method’ : ‘post’,**
** ‘contentType’: ‘application/json’,**
** ‘payload’ : JSON.stringify(data)**
** };**

** var response = UrlFetchApp.fetch(url, options);**
** var txt= response.getContentText();**
** var d=JSON.parse(txt);**

//RETURN RESULTS BACK TO GOOGLE SHEET

var sh1=SpreadsheetApp.getActiveSpreadsheet().getSheetByName(“MONITOR”);

sh1.getRange(1, 1).setValue(d);
}

Result:

{Role=PENDING, SyncState=SHARD SYNCING, Alert=true, CommitteeChain=2, NextEventMsg=12 to be COMMITEE, Status=ONLINE}

Now if I try the same thing, and switch the last line to:

sh1.getRange(1, 1).setValue(d.Role);
sh1.getRange(1, 2).setValue(d.SyncState);
sh1.getRange(1, 3).setValue(d.Alert);
sh1.getRange(1, 4).setValue(d.CommitteeChain);
sh1.getRange(1, 5).setValue(d.NextEventMsg);
sh1.getRange(1, 6).setValue(d.Status);

It completes its execution but returns nothing. Any ideas?


Solution

  • I tested your sample data and it returned to separate cells as expected. But can you try this approach?

    Code:

    Object.keys(d).forEach(function (key, index){
      sh1.getRange(1, index + 1).setValue(d[key]);
    });
    

    Behavior:

    Output:

    output

    EDIT:

    d.forEach(function (data, row){
      Logger.log(data);
      Object.keys(data).forEach(function (key, index){
        Logger.log(key)
        sh.getRange(row + 1, index + 1).setValue(data[key]);
      });
    });
    

    Note:

    EDIT2:

    Code:

    // header
    sh.getRange(1, 1, 1, Object.keys(d[0]).length).setValues([Object.keys(d[0])]);
    // contents
    d.forEach(function (data, row){
      Object.keys(data).forEach(function (key, index){
        sh.getRange(row + 2, index + 1).setValue(data[key]);
      });
    });
    

    Output:

    output