带有嵌套JSON的JSON.parse()

时间:2018-02-23 20:56:17

标签: javascript json google-apps-script

我有一个调用CRM系统的google脚本,解析JSON并将其附加到工作表。它适用于某些端点,而不适用于其他端点。当它工作时,g表中的值,当它没有它只是没有找到任何值。代码:

function thingy() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheets = ss.getSheets();
  var sheet = ss.getActiveSheet();

  var url    = "https://api.pipedrive.com/v1/mailbox/mailMessages/17685?include_body=1";
  var token  = "&api_token=token"

  var response = UrlFetchApp.fetch(url+token); 
  var dataSet = JSON.parse(response.getContentText()); 
  var data;

  for (var i = 0; i < dataSet.data.length; i++) {
    data = dataSet.data[i];
    sheet.appendRow([data.user_id]); 
  }
}

端点JSON有效,我可以使用sheet.appendRow获取标题([data.title]:

{
"success": true,
"data": [
    {
        "stage_id": 6,
        "title": "Fakel",
        "value": 210,
        "currency": "EUR",
        "add_time": "2014-02-25 09:09:01"
    }

没有工作的端点JSON,我无法通过sheet.appendRow([data.body]:

获取正文
{
"data": {
    "id": 17685,
    "from": [
        {
            "id": 1411,
        }
    ],
    "to": [
        {
            "id": 1739,
        }
    ],
    "cc": [
        {
            "id": 199,
     }
    ],
    "bcc": [],
    "body": "blahblahblah"

我也想获得子实体。所以我希望能够在From,TO,CC中获取ID。我猜JSON的结构有什么不同,这阻止我这样做?

2 个答案:

答案 0 :(得分:1)

在第一个示例中,dataSet.data是一个数组,因此您可以遍历元素并在循环中以dataSet.data[i]的形式访问每个元素。

在第二个示例中,dataSet.data是一个对象,而不是一个数组,因此没有要循环的数组元素。您想要的信息位于dataSet.data.body

sheet.appendRow([dataSet.data.body])

答案 1 :(得分:0)

&#13;
&#13;
function thingy() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheets = ss.getSheets();
  var sheet = ss.getActiveSheet();

  var url    = "https://api.pipedrive.com/v1/mailbox/mailMessages/17685?include_body=1";
  var token  = "&api_token=token"

  var response = UrlFetchApp.fetch(url+token); 
  var dataSet = JSON.parse(response.getContentText()); 
  var data;

  // Right here, you are looping over the .data property, which doesn't exist and you are thinking that you can access it with the data.body property. The problem being that the second response .data property is an OBJECT and not an ARRAY (like it is in your first response example).
  for (var i = 0; i < dataSet.data.length; i++) {
    data = dataSet.data[i];
    sheet.appendRow([data.user_id]); 
  }
}
&#13;
&#13;
&#13;