我有一個谷歌電子表格,其中 A列中有JSON,我想用相應行和列的資料填充 Sheet B。但是,我不完全確定如何開始。我對整個程序有點困惑。第一個申報表。我見過人們使用以下內容:
function parseJSON()
{
var ss = SpreadsheetApp.getActiveSpreadsheet(); // Gets the Active Spreadsheet
var sheet = ss.getSheets()[0]; // Gets the first sheet
var parsed = JSON.parse(json);
sheet.appendRow([json.items[i].id, json.items[i].name, json.items[i].url]);
}
但我有 1 個活動電子表格,從作業表 A 到作業表 B。所以我需要宣告第二張作業表(我的作業表 B)嗎?
var ss = SpreadsheetApp.getActiveSpreadsheet(); // Gets the Active Spreadsheet
var sheet1 = ss.getSheets()[0]; // Gets the first sheet
var sheet2 = ss.getSheets()[1]; // Gets the first sheet
sheet2.appendRow([json.items[i].id, json.items[i].name, json.items[i].url]);
或者我不需要那些宣告,我只是
function parseJSON(parsed)
{
return [parsed.items[i].id, parsed.items[i].name, parsed.items[i].url]
}
所以在 Sheet B A1 我只是放了 =parseJSON(SheetB!A) 或者我仍然不確定的等價物。
另外,我如何根據 JSON 宣告什么是標頭和值?是否應該宣告標題?
const headers = ["dish_name","dish_price","dish_quantity"];
或者是否可以從 JSON 中獲取標頭?對應的值呢?Apps Ssripts 是否接受 foreach 回圈?
對于其他背景關系(對于有幫助的選定答案)
JSON 物件 - {"55":{"dish_name":"(Ala Carte) Claypot Soup with Rice and Char Kuih","dish_price":17,"dish_quantity":1,"dish_size_name":"default","dish_size_price":0,"dish_addon_name":"default","dish_addon_price":0,"dish_variation_name":"default","dish_variation_price":0}}
所選答案能夠將其拆分為鍵值對。所以常量鍵是標題,行是相應的值。
uj5u.com熱心網友回復:
在你的情況下,下面的修改如何?
改裝要點:
關于您的以下腳本,
function parseJSON() { var ss = SpreadsheetApp.getActiveSpreadsheet(); // Gets the Active Spreadsheet var sheet = ss.getSheets()[0]; // Gets the first sheet var parsed = JSON.parse(json); sheet.appendRow([json.items[i].id, json.items[i].name, json.items[i].url]); }- 在這種情況下,
sheet,json不被宣告。這樣,就會發生錯誤。 - 當
sheet,json被宣告時,parsed不使用。
- 在這種情況下,
回答問題 1:
但我有 1 個活動電子表格,從作業表 A 到作業表 B。所以我需要宣告第二張作業表(我的作業表 B)嗎?我認為是的。我認為當您想從“A”表的“A”列中檢索值并將值放入“B”表時,需要宣告兩個表。
回答問題 2:
另外,我如何根據 JSON 宣告什么是標頭和值?是否應該宣告標題?或者是否可以從 JSON 中獲取標頭?對應的值呢?Apps Ssripts 是否接受 foreach 回圈?
我認為是的。當我看到您的 JSON 資料時,似乎存在幾個屬性。而且,在您的輸出情況下,需要按順序排列這些值。在這種情況下,當使用標頭值時,可以輕松準備腳本。
示例腳本:
為了實作您的目標,以下示例腳本如何?
function myFunction() {
// 1. Retrieve source and destination sheets.
const ss = SpreadsheetApp.getActiveSpreadsheet();
const [srcSheet, dstSheet] = ["Sheet1", "Sheet2"].map(s => ss.getSheetByName(s));
// 2. Retrieve values from source sheet.
const values = srcSheet.getRange("A1:A" srcSheet.getLastRow()).getValues();
// 3. Create an array for putting to the destination sheet using the header value.
const headers = ["dish_name","dish_price","dish_quantity"];
const ar = [["", ...headers], ...values.flatMap(([a]) => Object.entries(JSON.parse(a)).map(([k, v]) => [k, ...headers.map(h => v[h] || "")]))];
// 4. Put the array to the destination sheet.
dstSheet.getRange(1, 1, ar.length, ar[0].length).setValues(ar);
}
- 此示例腳本從源作業表“Sheet1”的“A”列中檢索值,并將這些值轉換為二維陣列并將該陣列放入目標作業表“Sheet2”。
- 請根據您的實際情況分別修改源“Sheet1”和目標“Sheet2”作業表的作業表名稱。
參考:
- 地圖()
- 獲取值()
- 設定值(值)
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/372959.html
