我使用Google Apps Script urlFetchApp
函数创建了以下嵌套JSON。如何动态从项目中获取所有键并将它们Map到各自的列标题?实际数据有更多的键,因此寻找一种动态的方式。
列应该是,
name, description, owner_display_name, owner_external_urls, owner_type, urls_site, images_1_height, images_1_url, images_2_height, images_2_url
{
"href":"https://api.example.com/",
"items":[
{
"name":"test",
"description":"desc",
"owner":{
"display_name":"name",
"external_urls":{"site":"www.example.com"},
"type":"user"
},
"urls":{"site":"www.google.com"},
"images":[
{"height":640,"url":"www.google.com"},
{"height":300,"url":"www.google.com"}
]
},{
"name":"test2",
"description":"desc2",
"owner":{
"display_name":"name2",
"external_urls":{"site":"www.example.com"},
"type":"user2"
},
"urls":{"site":"www.google.com"},
"images":[
{"height":640,"url":"www.google.com"},
{"height":300,"url":"www.google.com"}
]
}
]
}
下面是我的代码,它是静态的。
function JSONtoSheet() {
const json = '{ "href":"https://api.example.com/", "items":[ { "name":"test", "description":"desc", "owner":{ "display_name":"name", "external_urls":{"site":"www.example.com"}, "type":"user" }, "urls":{"site":"www.google.com"}, "images":[ {"height":640,"url":"www.google.com"}, {"height":300,"url":"www.google.com"} ] },{ "name":"test2", "description":"desc2", "owner":{ "display_name":"name2", "external_urls":{"site":"www.example.com"}, "type":"user2" }, "urls":{"site":"www.google.com"}, "images":[ {"height":640,"url":"www.google.com"}, {"height":300,"url":"www.google.com"} ] } ] }';
const data = JSON.parse(json);
const sheet = SpreadsheetApp.getActive().getSheetByName('Test');
sheet.clear();
var headers = [
["Name","Description","Owner Display Name","Owner Type","Owner External URL","Site URL","Image Height 1","Image URL 1","Image Height 2","Image URL 2"]
];
var range = sheet.getRange("A1:J1");
range.setValues(headers);
const items = data.items;
for (let i = 0; i < items.length; i++) {
const item = items[i];
const name = item.name;
const desc = item.description;
const owner = item.owner;
const ownerDisplayName = owner.display_name;
const ownerType = owner.type;
const ownerExternalURL = owner.external_urls.site;
const siteURL = item.urls.site;
const images = item.images;
const imageHeight1 = images[0].height;
const imageURL1 = images[0].url;
const imageHeight2 = images[1].height;
const imageURL2 = images[1].url;
sheet.getRange(i+2, 1).setValue(name);
sheet.getRange(i+2, 2).setValue(desc);
sheet.getRange(i+2, 3).setValue(ownerDisplayName);
sheet.getRange(i+2, 4).setValue(ownerType);
sheet.getRange(i+2, 5).setValue(ownerExternalURL);
sheet.getRange(i+2, 6).setValue(siteURL);
sheet.getRange(i+2, 7).setValue(imageHeight1);
sheet.getRange(i+2, 8).setValue(imageURL1);
sheet.getRange(i+2, 9).setValue(imageHeight2);
sheet.getRange(i+2, 10).setValue(imageURL2);
}
}
1条答案
按热度按时间rta7y2nd1#
你可以使用这段代码来动态地从条目中获取所有的键,并将它们Map到它们自己的单独的列标题: