[英]How to get all lists available on a json Array with google Apps script
我是 GAS 的初学者,我正在寻求帮助来完成我的脚本,我的目标是从公共 Api 获取数据,实际上我能够编写代码来检索数据,但我仍然无法从 arrays 中提取所有数据,例如:
"isLabeledBy": [
{
"attributedAt": null,
"endDate": null,
"detail": [],
"isConceptualizedBy": {
"code": "10055",
"pictureUrl": "https://smedia.alkemics.com/api/1/concept/10055/picture/logo/original.png",
"description": "",
"label": "Cosmebio"
},
"value": null,
"startDate": null
},
{
"attributedAt": null,
"endDate": null,
"detail": [],
"isConceptualizedBy": {
"code": "80002",
"pictureUrl": "https://smedia.alkemics.com/api/1/concept/80002/picture/logo/original.png",
"description": "",
"label": "Triman"
},
"value": null,
"startDate": null
},
{
"attributedAt": null,
"endDate": null,
"detail": [],
"isConceptualizedBy": {
"code": "ECOCERT_COSMETIQUE_ECO",
"pictureUrl": "https://smedia.alkemics.com/api/1/concept/100230755/picture/logo/original.png",
"description": "",
"label": "Ecocert - Cosmétique Écologique"
},
"value": null,
"startDate": null
},
{
"attributedAt": null,
"endDate": null,
"detail": [],
"isConceptualizedBy": {
"code": "19095",
"pictureUrl": "https://smedia.alkemics.com/api/1/concept/19095/picture/logo/original.png",
"description": "",
"label": "European Organic Agriculture"
},
"value": null,
"startDate": null
},
{
"attributedAt": null,
"endDate": null,
"detail": [],
"isConceptualizedBy": {
"code": "72117",
"pictureUrl": "https://smedia.alkemics.com/api/1/concept/72117/picture/logo/original.png",
"description": "",
"label": "Concours des vins Elle à Table 2017 - Or"
},
"value": null,
"startDate": null
}
],
这里我们有一个 json 数组,我需要与属性 label 对应的数据,但是我的脚本只允许我获取数组中的第一个而不是其他四个(我可以通过更改脚本中的索引来获得其他的,但是不是第五个)。
第一个:“标签”:“Cosmebio”
其他四个:“label”:“Concours des vins Elle à Table 2017 - Or”“label”:“European Organic Agriculture”“label”:“Ecocert - Cosmétique Écologique”“label”:“Triman”
我的脚本图片:在此处输入图片描述
var lesparams =params + '&limit=' + limit + '&next_page=' + next_page + '&ts=' + Math.floor((Math.random() * 10000000) + 1);
var url='https://apis.alkemics.com/public/v1/products?'+lesparams;
var content =UrlFetchApp.fetch(url, options);
if (content.getResponseCode() ==200) {
var retour =JSON.parse(content.getContentText());
next_page=retour.next_page;
var data=retour.data;
for(i=0; i<data.length;i++) {
var produit=data[i]; // Un produit au format JSON
var line=[
produit.isLabeledBy[0] != null? produit.isLabeledBy[0].isConceptualizedBy.label:'',
];
produits.push(ligne);
total=total+1;
}
}
else {
Logger.log('Error in GET /contents/{contentid}')
}
有人可以帮我改进脚本吗?
谢谢
我相信你的目标如下。
从您All the values corresponding to the attribute Label: "label": "Cosmebio", "label": "Triman" "label": "Ecocert - Cosmétique Écologique"..
以及您的问题,您想检索"Cosmebio", "Triman", "Ecocert - Cosmétique Écologique"..
来自您的展示数据。
在您的情况下,根据您的脚本和显示数据,它假设 API 中的content.getContentText()
的值可能是{"data": [{"isLabeledBy": [### your showing data ###]},{"isLabeledBy": [### your showing data ###]},,,]}
。
如果我的猜测是正确的,那么在您当前的脚本中, produit.isLabeledBy[0]
会在每个循环中使用。 这样,仅检索"isLabeledBy"
的第一个元素。 我认为这可能是您的问题的原因, but my script allows me to get only the first one in the array but not the four others
。
在这种情况下,下面的示例脚本怎么样?
var data=retour.data;
for(i=0; i<data.length;i++) {
var produit=data[i]; // Un produit au format JSON
var line=[
produit.isLabeledBy[0] != null? produit.isLabeledBy[0].isConceptualizedBy.label:'',
];
produits.push(ligne);
total=total+1;
}
var data = retour.data;
var result = data.map(({isLabeledBy}) => isLabeledBy.map(o => o.isConceptualizedBy?.label || ""));
在此修改中,结果值作为数组data
的每个元素返回。 就像[['Cosmebio','Triman','Ecocert - Cosmétique Écologique','European Organic Agriculture','Concours des vins Elle à Table 2017 - Or','Cosmebio'],,,]
。 如果要将结果检索为一维数组,请进行如下修改。
从
var result = data.map(({isLabeledBy}) => isLabeledBy.map(o => o.isConceptualizedBy?.label || ""));
至
var result = data.flatMap(({isLabeledBy}) => isLabeledBy.map(o => o.isConceptualizedBy?.label || ""));
或者,如果要将结果值放在一列,请使用
var result = data.flatMap(({isLabeledBy}) => isLabeledBy.map(o => [o.isConceptualizedBy?.label || ""]));
非常感谢您花时间回答我的问题,我的 API 包含项目列表和有关它的信息,我必须显示与每个标题对应的数据(这是我的信息的标题寻找)其中一个标题是“标签”,当我使用您推荐的脚本时,我为第一项获得的相同数据显示在 header“标签”下方的所有其他项目中,
[`
var url='https://apis.alkem.com/public/v1/products?'+params; var content =UrlFetchApp.fetch(url, options); if (content.getResponseCode() ==200) { var returne =JSON.parse(content.getContentText()); next_page=retour.next_page; var data=returne.data; for(i=0; i<data.length;i++) { var produit=data[i]; // Un produit au format JSON var labio = data.map(({isLabeledBy}) => isLabeledBy.map(o => o.isConceptualizedBy?.label || "")) Logger.log(labio) var ligne=[ labio.map(r => r.join(",")).join("\n"), ]; produits.push(ligne); total=total+1; } } else { Logger.log('Error in GET /contents/{contentid}') }
`] 2
我的文件是一个 API 调用,通过输入一个输入值“gtin”来检索几个“产品”的信息。
我检索此信息的脚本如下:
function GetAllProduct() {
var token=ConnectAlkemics();
var headers ={
"accept": "*/*",
"accept-language": "fr",
'Authorization' : 'Bearer ' + token,
'cache-control': 'no-cache',
'content-type': 'application/json;charset=UTF-8',
'expires': '-1',
'pragma': 'no-cache',
'sec-fetch-dest': 'empty',
'sec-fetch-mode': 'cors',
'sec-fetch-site': 'same-site',
'x-alk-priority': '9'
};
var options ={
'method' : "GET",
"headers" : headers
};
var source =SpreadsheetApp.getActive().getSheetByName("GTIN");
var ss =SpreadsheetApp.getActive().getSheetByName("RESULTATS");
ss.clear();
var total=0;
var debut=2;
var moregtin=true
var lignegtin=1;
var colonnes=[
"GTIN",
"Libelle long",
"Libelle Court",
"Fournisseur",
"Catégorie du produit",
"Code Tiers",
"Cycle de vie",
"Maturité commande Galec",
"Maturité direct magasin" ,
"Maturité Commande SCABEL",
"Maturité complémentaire Galec",
"Maturité complémentaire Direct Magasin",
"Maturité complémentaire Scabel",
"Maturité Animation Digitale",
"Agence de certification",
"Label",
"Certificat Biologique",
];
var colonnematurite=10; //Colonnes
for(i=0;i<colonnes.length;i++) {
ss.getRange(1,i+1).setValue(colonnes[i]);
}
while (moregtin==true)
{
var fini=false;
var nbgtin=0;
var lesgtin=""
var produits =[];
while ((source.getRange(lignegtin,1).getValue()!="") && (nbgtin<50)) //paquets de 50 GTINs
{
if (lesgtin!="")
lesgtin=lesgtin+",";
lesgtin=lesgtin+source.getRange(lignegtin,1).getValue();
lignegtin=lignegtin+1;
nbgtin=nbgtin+1;
}
if (lesgtin=="")
{
moregtin=false;
fini=true;
}
else
{
var limit=200;
var next_page='';
var lastparam='';
var params =lastparam + //'status_shared_from=4' +
'&filter_product_languages=fr&filter_gtins_in=' + lesgtin + '&filter_source_include=uuid,gtin,namePublicLong,namePublicShort,isSharedFrom.sourceOrganization.nameLegal,endAvailabilityDateTime,supplierId,business_processes,brand.description,lastOrderDateTime,isUserLabeledByName,lifeCycle,typePackaging,isConsumerUnit,isBaseUnit,isDisplayUnit,certificationInformationList,assets.documents,fileName,updatedAt,isLabeledBy,partyInformationList,endAvailabilityDateTime,isLabeledBy[0].isConceptualizedBy'
var lesparams =params + '&limit=' + limit + '&next_page=' + next_page + '&ts=' + Math.floor((Math.random() * 10000000) + 1);
}
while (fini==false) {
var lesparams =params + '&limit=' + limit + '&next_page=' + next_page + '&ts=' + Math.floor((Math.random() * 10000000) + 1);
var url='https://apis.alkemics.com/public/v1/products?'+lesparams;
//Logger.log(url);
var content =UrlFetchApp.fetch(url, options);
//Logger.log(content);
//Logger.log(content.getResponseCode())
if (content.getResponseCode() ==200) {
var retour =JSON.parse(content.getContentText());
next_page=retour.next_page;
var data=retour.data;
for(i=0; i<data.length;i++) {
var produit=data[i]; // Un produit au format JSON
var libellelong="";
try
{
libellelong=produit.namePublicLong[0].data;
}
catch(e) {
libellelong="";
//libelle="NA"
}
var libellecourt="";
try
{
libellecourt=produit.namePublicShort[0].data;
}
catch(e) {
libellecourt="";
//libelle="NA"
}
var maturite={}
for(k=0;k<produit.business_processes.length;k++)
{
maturite[produit.business_processes[k].label]=(produit.business_processes[k].requested==false?"":(produit.business_processes[k].status==true?"OK":"KO"));
}
var listematurite={}
for(k=0;k<produit.business_processes.length;k++)
{
listematurite[k]=produit.business_processes[k].label;
}
var marque=""
if ("brand" in produit) {
if ("description" in produit.brand)
marque=produit.brand.description;
}
var labio = produit.map(({isLabeledBy}) => isLabeledBy.map(o => o.isConceptualizedBy?.label || ""))
Logger.log(labio)
var ConsumerUnit = (produit.isConsumerUnit == false ?"":(produit.isBaseUnit==true?"UC":"LOT"))
var Presentoir = (produit.isDisplayUnit == true ? produit.typePackaging.label : "")
var ligne=[
produit.gtin,
libellelong,
produit.namePublicShort[0].data,
produit.isSharedFrom[0].sourceOrganization.nameLegal,
produit.kind != null? produit.kind.label: ' ',
produit.supplierId,
produit.lifeCycle,
maturite[ss.getRange(1,colonnematurite).getValue()],
maturite[ss.getRange(1,colonnematurite+1).getValue()],
maturite[ss.getRange(1,colonnematurite+2).getValue()],
maturite[ss.getRange(1,colonnematurite+3).getValue()],
maturite[ss.getRange(1,colonnematurite+4).getValue()],
maturite[ss.getRange(1,colonnematurite+5).getValue()],
maturite[ss.getRange(1,colonnematurite+6).getValue()],
maturite[ss.getRange(1,colonnematurite+7).getValue()],
maturite[ss.getRange(1,colonnematurite+8).getValue()],
produit.certificationInformationList[0].certificationAgencyCode.label: '',
labio.map(r => r.join(",")).join("\n"),
produit.assets.documents[0] != null?
produit.assets.documents[0].uniformResourceIdentifier: '',
];
produits.push(ligne);
total=total+1;
}
}
else {
Logger.log('Error in GET /contents/{contentid}')
}
每个属性的数据都会输出到工作表中的相应部分。
所有 output 值都是数字或句子的形式,除了你帮助我的 label 属性,它是元素列表。
通过应用您建议我执行的脚本,我设法恢复仅输入的第一个“gtin”产品的“标签”数据,而不是 rest、rest 对应的“标签”列的 Z65E8800B5C68A6AAD88填充与第一个产品相同的值,而不是应该显示的匹配值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.