很复杂!
JSON 和类似电子表格的数据不太容易结合在一起,因为 JSON 本质上是嵌套的,这不容易以表格方式表示。通常,键每次都会以不同的顺序出现,这就是为什么您可能会得到不一致的结果。
出于这个原因,我建议您熟悉 Apps Script,因为它是一种与 JSON 交互的方式比通过表单函数更友好。这样您就可以轻松地按名称调用值,因为 JSON 毕竟是 JavaScript 对象表示法,而 Apps Script 是一种 JavaScript!
示例应用程序脚本
为了说明这一点,这是我刚刚编写的一个脚本,用于从您发布的特定 JSON 中提取数据。它也可以作为工作表中的功能。下面演示如何使用它:
/**
* 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 的结构。
参考文献