Google Script JSON вложенные массивы в ячейку - PullRequest
2 голосов
/ 19 июня 2020

Я пытаюсь прочитать части следующих JSON в листах Google, похоже, есть вложенные массивы, которые мне трудно вставить в одну ячейку ... main JSON

{
  "lineItems": [
    {
      "name": "advertisers/1558261/lineItems/12317016",
      "advertiserId": "1238261",
      "campaignId": "1233305",
      "insertionOrderId": "13016372",
      "lineItemId": "12317016",
      "displayName": "All | Routes| All Users | ABC | ABC-LI1",
      "lineItemType": "LINE_ITEM_TYPE_DISPLAY_DEFAULT",
      "entityStatus": "ENTITY_STATUS_ACTIVE",
      "updateTime": "2020-04-15T12:51:42.929Z",
      "partnerCosts": [
        {
          "costType": "PARTNER_COST_TYPE_THIRD_PARTY_AD_SERVER",
          "feeType": "PARTNER_COST_FEE_TYPE_CPM_FEE",
          "feeAmount": "1000000",
          "invoiceType": "PARTNER_COST_INVOICE_TYPE_PARTNER"
        },
        {
          "costType": "PARTNER_COST_TYPE_DOUBLE_VERIFY_PREBID",
          "feeType": "PARTNER_COST_FEE_TYPE_CPM_FEE",
          "feeAmount": "0",
          "invoiceType": "PARTNER_COST_INVOICE_TYPE_DV360"
        },
        {
          "costType": "PARTNER_COST_TYPE_DV360_FEE",
          "feeType": "PARTNER_COST_FEE_TYPE_MEDIA_FEE",
          "feePercentageMillis": "0",
          "invoiceType": "PARTNER_COST_INVOICE_TYPE_DV360"
        },
        {
          "costType": "PARTNER_COST_TYPE_DEFAULT",
          "feeType": "PARTNER_COST_FEE_TYPE_MEDIA_FEE",
          "feePercentageMillis": "0",
          "invoiceType": "PARTNER_COST_INVOICE_TYPE_PARTNER"
        }
      ],
      "flight": {
        "flightDateType": "LINE_ITEM_FLIGHT_DATE_TYPE_CUSTOM",
        "dateRange": {
          "startDate": {
            "year": 2020,
            "month": 4,
            "day": 15
          },
          "endDate": {
            "year": 2020,
            "month": 4,
            "day": 30
          }
        }
      },
      "budget": {
        "budgetAllocationType": "LINE_ITEM_BUDGET_ALLOCATION_TYPE_UNLIMITED",
        "budgetUnit": "BUDGET_UNIT_CURRENCY"
      },
      "pacing": {
        "pacingPeriod": "PACING_PERIOD_DAILY",
        "pacingType": "PACING_TYPE_EVEN",
        "dailyMaxMicros": "40100000"
      },
      "frequencyCap": {
        "timeUnit": "TIME_UNIT_DAYS",
        "timeUnitCount": 1,
        "maxImpressions": 5
      },
      "partnerRevenueModel": {
        "markupType": "PARTNER_REVENUE_MODEL_MARKUP_TYPE_TOTAL_MEDIA_COST_MARKUP"
      },
      "conversionCounting": {
        "postViewCountPercentageMillis": "100000",
        "floodlightActivityConfigs": [
          {
            "1fI": "7517101",
            "3PCdays": 30,
            "2PVdays": 30
          },
          {
            "1fI": "7541802",
            "3PCdays": 30,
            "2PVdays": 30
          },
          {
            "1fI": "7552803",
            "3PCdays": 30,
            "2PVdays": 30
          },
          {
            "1fI": "7517104",
            "3PCdays": 30,
            "2PVdays": 30
          }
        ]
      },
      "bidStrategy": {
        "fixedBid": {
          "bidAmountMicros": "3610000"
        }
      },
      "integrationDetails": {}
    },
    {
      "name": "advertisers/1558261/lineItems/12317017",
      "advertiserId": "1238261",
      "campaignId": "1233305",
      "insertionOrderId": "13016372",
      "lineItemId": "12317017",
      "displayName": "All | Routes| All Users | ABC | ABC-LI2",
      "lineItemType": "LINE_ITEM_TYPE_DISPLAY_DEFAULT",
      "entityStatus": "ENTITY_STATUS_ACTIVE",
      "updateTime": "2020-04-01T16:06:19.831Z",
      "partnerCosts": [
        {
          "costType": "PARTNER_COST_TYPE_THIRD_PARTY_AD_SERVER",
          "feeType": "PARTNER_COST_FEE_TYPE_CPM_FEE",
          "feeAmount": "1000000",
          "invoiceType": "PARTNER_COST_INVOICE_TYPE_PARTNER"
        },
        {
          "costType": "PARTNER_COST_TYPE_DOUBLE_VERIFY_PREBID",
          "feeType": "PARTNER_COST_FEE_TYPE_CPM_FEE",
          "feeAmount": "0",
          "invoiceType": "PARTNER_COST_INVOICE_TYPE_DV360"
        },
        {
          "costType": "PARTNER_COST_TYPE_DV360_FEE",
          "feeType": "PARTNER_COST_FEE_TYPE_MEDIA_FEE",
          "feePercentageMillis": "0",
          "invoiceType": "PARTNER_COST_INVOICE_TYPE_DV360"
        },
        {
          "costType": "PARTNER_COST_TYPE_DEFAULT",
          "feeType": "PARTNER_COST_FEE_TYPE_MEDIA_FEE",
          "feePercentageMillis": "0",
          "invoiceType": "PARTNER_COST_INVOICE_TYPE_PARTNER"
        }
      ],
      "flight": {
        "flightDateType": "LINE_ITEM_FLIGHT_DATE_TYPE_CUSTOM",
        "dateRange": {
          "startDate": {
            "year": 2020,
            "month": 4,
            "day": 15
          },
          "endDate": {
            "year": 2020,
            "month": 4,
            "day": 30
          }
        }
      },
      "budget": {
        "budgetAllocationType": "LINE_ITEM_BUDGET_ALLOCATION_TYPE_UNLIMITED",
        "budgetUnit": "BUDGET_UNIT_CURRENCY"
      },
      "pacing": {
        "pacingPeriod": "PACING_PERIOD_DAILY",
        "pacingType": "PACING_TYPE_EVEN",
        "dailyMaxMicros": "26730000"
      },
      "frequencyCap": {
        "timeUnit": "TIME_UNIT_DAYS",
        "timeUnitCount": 1,
        "maxImpressions": 5
      },
      "partnerRevenueModel": {
        "markupType": "PARTNER_REVENUE_MODEL_MARKUP_TYPE_TOTAL_MEDIA_COST_MARKUP"
      },
      "conversionCounting": {
        "postViewCountPercentageMillis": "100000"
      },
      "bidStrategy": {
        "fixedBid": {
          "bidAmountMicros": "3610000"
        }
      },
      "integrationDetails": {}
    }
  ]
}

из floodlightActivityConfigs Мне нужно, чтобы эти массивы находились в одной ячейке, как

{ "1fI": "72217193", "3PCdays": 30, "2PVdays": 30 },{ "1fI": "75221840", "3PCdays": 30, "2PVdays": 30 }, { "1fI": "75222864", "3PCdays": 30, "2PVdays": 30 }, { "1fI": "75333184", "3PCdays": 30, "2PVdays": 30 }

, однако, когда я пытаюсь сделать sh их, только первая часть печатается, из примера JSON второй объект не имеет сведений о floodlightActivityConfigs, и это ожидается

Мой код ниже со встроенным JSON, просто не могу понять это

function testAPI2(){

  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Mysheet');

  var response =  {"lineItems":[{"name":"advertisers/1558261/lineItems/12317016","advertiserId":"1238261","campaignId":"1233305","insertionOrderId":"13016372","lineItemId":"12317016","displayName":"All | Routes| All Users | ABC | ABC-LI1","lineItemType":"LINE_ITEM_TYPE_DISPLAY_DEFAULT","entityStatus":"ENTITY_STATUS_ACTIVE","updateTime":"2020-04-15T12:51:42.929Z","partnerCosts":[{"costType":"PARTNER_COST_TYPE_THIRD_PARTY_AD_SERVER","feeType":"PARTNER_COST_FEE_TYPE_CPM_FEE","feeAmount":"1000000","invoiceType":"PARTNER_COST_INVOICE_TYPE_PARTNER"},{"costType":"PARTNER_COST_TYPE_DOUBLE_VERIFY_PREBID","feeType":"PARTNER_COST_FEE_TYPE_CPM_FEE","feeAmount":"0","invoiceType":"PARTNER_COST_INVOICE_TYPE_DV360"},{"costType":"PARTNER_COST_TYPE_DV360_FEE","feeType":"PARTNER_COST_FEE_TYPE_MEDIA_FEE","feePercentageMillis":"0","invoiceType":"PARTNER_COST_INVOICE_TYPE_DV360"},{"costType":"PARTNER_COST_TYPE_DEFAULT","feeType":"PARTNER_COST_FEE_TYPE_MEDIA_FEE","feePercentageMillis":"0","invoiceType":"PARTNER_COST_INVOICE_TYPE_PARTNER"}],"flight":{"flightDateType":"LINE_ITEM_FLIGHT_DATE_TYPE_CUSTOM","dateRange":{"startDate":{"year":2020,"month":4,"day":15},"endDate":{"year":2020,"month":4,"day":30}}},"budget":{"budgetAllocationType":"LINE_ITEM_BUDGET_ALLOCATION_TYPE_UNLIMITED","budgetUnit":"BUDGET_UNIT_CURRENCY"},"pacing":{"pacingPeriod":"PACING_PERIOD_DAILY","pacingType":"PACING_TYPE_EVEN","dailyMaxMicros":"40100000"},"frequencyCap":{"timeUnit":"TIME_UNIT_DAYS","timeUnitCount":1,"maxImpressions":5},"partnerRevenueModel":{"markupType":"PARTNER_REVENUE_MODEL_MARKUP_TYPE_TOTAL_MEDIA_COST_MARKUP"},"conversionCounting":{"postViewCountPercentageMillis":"100000","floodlightActivityConfigs":[{"1fI":"7517101","3PCdays":30,"2PVdays":30},{"1fI":"7541802","3PCdays":30,"2PVdays":30},{"1fI":"7552803","3PCdays":30,"2PVdays":30},{"1fI":"7517104","3PCdays":30,"2PVdays":30}]},"bidStrategy":{"fixedBid":{"bidAmountMicros":"3610000"}},"integrationDetails":{}},{"name":"advertisers/1558261/lineItems/12317017","advertiserId":"1238261","campaignId":"1233305","insertionOrderId":"13016372","lineItemId":"12317017","displayName":"All | Routes| All Users | ABC | ABC-LI2","lineItemType":"LINE_ITEM_TYPE_DISPLAY_DEFAULT","entityStatus":"ENTITY_STATUS_ACTIVE","updateTime":"2020-04-01T16:06:19.831Z","partnerCosts":[{"costType":"PARTNER_COST_TYPE_THIRD_PARTY_AD_SERVER","feeType":"PARTNER_COST_FEE_TYPE_CPM_FEE","feeAmount":"1000000","invoiceType":"PARTNER_COST_INVOICE_TYPE_PARTNER"},{"costType":"PARTNER_COST_TYPE_DOUBLE_VERIFY_PREBID","feeType":"PARTNER_COST_FEE_TYPE_CPM_FEE","feeAmount":"0","invoiceType":"PARTNER_COST_INVOICE_TYPE_DV360"},{"costType":"PARTNER_COST_TYPE_DV360_FEE","feeType":"PARTNER_COST_FEE_TYPE_MEDIA_FEE","feePercentageMillis":"0","invoiceType":"PARTNER_COST_INVOICE_TYPE_DV360"},{"costType":"PARTNER_COST_TYPE_DEFAULT","feeType":"PARTNER_COST_FEE_TYPE_MEDIA_FEE","feePercentageMillis":"0","invoiceType":"PARTNER_COST_INVOICE_TYPE_PARTNER"}],"flight":{"flightDateType":"LINE_ITEM_FLIGHT_DATE_TYPE_CUSTOM","dateRange":{"startDate":{"year":2020,"month":4,"day":15},"endDate":{"year":2020,"month":4,"day":30}}},"budget":{"budgetAllocationType":"LINE_ITEM_BUDGET_ALLOCATION_TYPE_UNLIMITED","budgetUnit":"BUDGET_UNIT_CURRENCY"},"pacing":{"pacingPeriod":"PACING_PERIOD_DAILY","pacingType":"PACING_TYPE_EVEN","dailyMaxMicros":"26730000"},"frequencyCap":{"timeUnit":"TIME_UNIT_DAYS","timeUnitCount":1,"maxImpressions":5},"partnerRevenueModel":{"markupType":"PARTNER_REVENUE_MODEL_MARKUP_TYPE_TOTAL_MEDIA_COST_MARKUP"},"conversionCounting":{"postViewCountPercentageMillis":"100000"},"bidStrategy":{"fixedBid":{"bidAmountMicros":"3610000"}},"integrationDetails":{}}]};
  var data = JSON.parse(JSON.stringify(response));

  var LiData = data["lineItems"];

  
  
  var rows = [],
      data;
  for (i = 0; i < LiData.length; i++) {
      data = LiData[i];
      
     rows.push([
      data.campaignId, 
      data.conversionCounting.floodlightActivityConfigs
      ]);
    }

 dataRange = sheet.getRange(2, 1, rows.length,2).setValues(rows);

}

1 Ответ

1 голос
/ 19 июня 2020

Я считаю вашей целью следующее.

  • Вы хотите поместить объект { "1fI": "72217193", "3PCdays": 30, "2PVdays": 30 },,, в ячейку.

Для этого как насчет этой модификации?

Точка модификации:

  • В вашем скрипте data.conversionCounting.floodlightActivityConfigs - это массив. Чтобы поместить это в ячейку, введите JSON.stringify. Я думаю, что причина вашей проблемы в следующем.

Когда это отражено в вашем скрипте, измените его следующим образом.

Измененный скрипт:

От:
rows.push([
 data.campaignId, 
 data.conversionCounting.floodlightActivityConfigs
 ]);
Кому:
rows.push([
  data.campaignId, 
  JSON.stringify(data.conversionCounting.floodlightActivityConfigs)
]);

Ссылка:

Ответ на дополнительный вопрос:

  • Вы хотите отсортировать ключи от { "1fI": "72217193", "3PCdays": 30, "2PVdays": 30 } до { "1fI": "72217193", "2PVdays": 30,"3PCdays": 30... }.

К сожалению, объект JSON не гарантирует порядок. Например, этот поток полезен для понимания этого.

Но в вашем случае вы хотите поместить объект в ячейку в виде строки. Я подумал, что это можно использовать для решения вашего дополнительного вопроса. Поэтому в качестве обходного пути, когда { "1fI": "72217193", "3PCdays": 30, "2PVdays": 30 } не используется в качестве объекта JSON, я думаю, что порядок может быть установлен.

Измененный скрипт:

От:
rows.push([
 data.campaignId, 
 data.conversionCounting.floodlightActivityConfigs
 ]);
Кому:
rows.push([
  data.campaignId,
  data.conversionCounting.floodlightActivityConfigs ? `[${data.conversionCounting.floodlightActivityConfigs.map(e => `{${Object.entries(e).map(([k, v]) => typeof v == "number" ? `"${k}":${v}` : `"${k}":"${v}"`).sort().join(",")}}`).join(",")}]` : ""
]);
  • В этой модификации каждый объект преобразуется в массив со строкой и сортируется, а затем массив преобразуется в строку. Таким образом, ваша цель может быть достигнута.
  • В этом случае в ячейку помещается следующее значение:

    [{"1fI":"7517101","2PVdays":30,"3PCdays":30},{"1fI":"7541802","2PVdays":30,"3PCdays":30},{"1fI":"7552803","2PVdays":30,"3PCdays":30},{"1fI":"7517104","2PVdays":30,"3PCdays":30}]
    
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...