
[英]In Google Sheets, how can I output an array of IMPORTJSON() calls using a column as reference?
[英]Importing data using ImportJSON to Google Sheets, select value output based on column name?
我正在尝试将 Yahoo Finance 中的财务数据导入 Google 表格。 我刚刚了解了 ImportJSON。
我通过此链接使用 ImportJSON: https://query2.finance.yahoo.com/v10/finance/quoteSummary/EDIT?modules=defaultKeyStatistics
我的电子表格的 A 列中有股票代码,我想从上面的链接中为相应的代码提取某个值。
我试过这个:=INDEX(ImportJSON("https://query2.finance.yahoo.com/v10/finance/quoteSummary/"& A2&"?modules=defaultKeyStatistics"),2,69)
但是,由于我得到的结果好坏参半,该列似乎与每个股票代码的值不对应。
有没有办法让我使用列名而不是数字来索引?
JSON 和类似电子表格的数据不会很容易地将 go 放在一起,因为 JSON 本质上是嵌套的,这不容易以表格方式表示。 通常,键每次都会以不同的顺序出现,这就是为什么您可能会得到不一致的结果。
出于这个原因,我建议您熟悉 Apps Script,因为它是一种与 JSON 交互的方式比通过工作表函数更友好。 这样您就可以轻松地按名称调用值,因为 JSON 毕竟是 JavaScript Object 表示法,而 Apps Script 是一种 JavaScript!
为了说明这一点,这是我刚刚编写的一个脚本,用于从您发布的特定 JSON 中提取数据。 它也可以作为 function 在片材中使用。 下面演示如何使用它:
/**
* Returns 2D array of values. i.e.
* Value, Raw, Fmt, LongFmt
* sharesShort, 9890638, 9.89M, 9,890,638
*/
function getJsonValue(url) {
// Fetch the JSON
let response = UrlFetchApp.fetch(url);
let text = response.getContentText();
let json = JSON.parse(text);
// Initialize the output array
let output = [];
// Navigate to where the main data is
let stats = json.quoteSummary.result[0].defaultKeyStatistics
// Adding headers to the output
let header = ["Value", "Raw", "Fmt", "LongFmt"]
output.push(header)
// For each key in stats, add:
// Value, Raw, Fmt, LongFmt
for (let attribute in stats) {
// initialize row array
let row = [];
// Add Value to array
row.push(attribute);
// Check if the contents of the attribute is an object, else add blank row
if (typeof(stats[attribute]) == "object" && stats[attribute] != null) {
// if the object contains raw, fmt, longfmt, then add to row, else add null
"raw" in stats[attribute] ? row.push(stats[attribute].raw) : row.push(null)
"fmt" in stats[attribute] ? row.push(stats[attribute].fmt) : row.push(null)
"longFmt" in stats[attribute] ? row.push(stats[attribute].longFmt) : row.push(null)
} else {
row.push(null);
row.push(null);
row.push(null);
}
// Add row to output
output.push(row)
}
// Return 2D array
return output
}
你可以像这样使用它:
或在代码中:
function test() {
let file = SpreadsheetApp.getActive();
let sheet = file.getSheetByName("Sheet1");
let output = getJsonValue("https://query2.finance.yahoo.com/v10/finance/quoteSummary/EDIT?modules=defaultKeyStatistics")
let rows = output.length
let cols = output[0].length
let range = sheet.getRange(1,1,rows, cols)
range.setValues(output)
}
这个脚本主要是给你自己适配的,取决于你使用的JSON的结构。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.