从雅虎财经读取 JSON

问题描述 投票:0回答:1

我对来自 JSON 的数据有疑问。

JSON 示例链接:Apple 示例

我正在使用这段代码:

function yFinance(symbol) {
    const url = 'https://query2.finance.yahoo.com/v10/finance/quoteSummary/' + encodeURI(symbol) 
              + '?modules=price,assetProfile,summaryDetail,incomeStatementHistory,'
              + 'balanceSheetHistory,defaultKeyStatistics,financialData,calendarEvents,'
              + 'recommendationTrend,upgradeDowngradeHistory,majorHoldersBreakdown'
    ;
  
    const response = UrlFetchApp.fetch(url, {muteHttpExceptions: true});
    const responseCode = response.getResponseCode();
  
    if (responseCode === 200) {
        const quote = JSON.parse(response.getContentText());
        const paths = [
            'summaryDetail/dividendRate/raw',
            'summaryDetail/payoutRatio/raw'
        ];

        return getMatchingValues(getPath(quote, 'quoteSummary/result/0'), paths);
    }
    else
    {
        return -1; 
    }
}

function getPath( obj, path ) {
  if (!path || !obj) {
    return null;
  }
  const parts = path.split('/');
  const currentPath = parts[0];
  const nextPath = parts.slice(1).join('/');
  const currentObj = obj[currentPath];
  
  // final path, exit here
  if (nextPath.length === 0) {
    return currentObj;
  }
  
  if (Array.isArray( currentObj )) {
    // does an element exit at the next level
    if ( currentObj[parts[1]] ) {
      // will continue reading for 1 element
      return getPath( currentObj, nextPath );
    }
    // return all the subpaths, skip the ones that are falsy
    return currentObj.map( item => getPath( item, nextPath ) ).filter( v => v );
  }
  // get the next part of the object
  return getPath( currentObj, nextPath );
}


function getMatchingValues( obj, paths ) {
  return paths.flatMap( path => getPath( obj, path ));
}

代码来自这篇文章

因为我不是 JSON 专家,所以我有这个问题:

为什么我可以得到一些数据,而其他人的结果是空的?

我不明白其中的区别。

我试图在代码中将“dividendRate/raw”更改为“enterpriseValue/raw”或“ebitda/raw”,但它们返回 null 而不是特定数字。

谢谢

javascript json yahoo-finance
1个回答
-1
投票

OK 找到了解决方案。

对于“企业价值”:

  • 而不是'summaryDetail/dividendRate/raw'
  • 是'defaultKeyStatistics/dividendRate/raw'

对于“ebitda/raw”:

  • 而不是'summaryDetail/ebitda/raw'
  • 是“财务数据/ebitda/原始”
© www.soinside.com 2019 - 2024. All rights reserved.