Нужна помощь в чтении файла JSON без ввода имени

Я хочу, чтобы пользовательский тип в поисковом запросе, и я могу поместить его в переменную php, как это var symbol = php echo $tickerSearch; но я не знаю, как положить его в data.MSFT.quote.companyName и извлеките биржевую бирку "MSFT", как я могу ввести data.symbol.quote.companyName и прочитайте код data.MSFT.quote.companyNameтак что если это возможно в файле JSON, который я читаю, могу ли я пропустить элемент вроде data{1} (аналогично data[1])

<table style="width: 100%;">
    <tbody>

        <tr><!-- title Holder -->
            <td>
                <div style="background-color: #a1caff;" id="title-div"> 
                    <p style="margin-bottom: 0px;" id="exchangeTd"><b id="companyNameTd">[MSFT] </b> - </p>
                </div>
            </td>
        </tr>

        </tr>
            <td id="sectorTd"></td>
        <tr>

        <tr><!-- Div that Holds Stock Data -->
            <td><div id="data-div"></div></td>
        </tr>

    </tbody>
</table>

<!-- ===================== JAVASCRIPT ===================== -->
<script>
    //=== VARIABLES
    var request = new XMLHttpRequest();
    var containerDiv = document.getElementById('data-div');
    var symbol = "msft";

    //Use IEX API funmction "GET" to recieve data 
    request.open ('GET', `https://api.iextrading.com/1.0/stock/market/batch?symbols=${symbol}&types=quote,stats,earnings,financials`)

    //send the request to the server
    request.send() 

    //Request onload     
    request.onload = function() {
        //convert to readable file
        var iexData = JSON.parse(request.responseText);

        //check to see if its a good search or bad
        if (request.status == 200) {
            createStockData();
            outputToHTML(iexData);
        }
    };

    //=== FUNCTION that creats the table to put into html' 1/2
    function createStockData() {
        //Assemble the whole table here
        let assembler = document.createElement('div');

        assembler.innerHTML = `
            <table style="width: 100%; background-color: #a1caff;">
                <tbody>
                    <tr>
                        <td>Last</td>
                        <td><b id="lastTd"></b></td>

                        <td>Change</td>
                        <td><b id="changeTd"></b></td>

                        <td>Change %</td>
                        <td><b id="changePctTd"></b></td>

                        <td>Volume</td>
                        <td><b id="volumeTd"></b></td>
                    </tr>

                    <tr>
                        <td>Market Cap</td>
                        <td><b id="mktCpTd"></b></td>

                        <td>Dividend</td>
                        <td><b id="dividendTd"></b></td>

                        <td>Dividend %</td>
                        <td><b id="dividendPctTd"></b></td>
                    </tr>                        
                </tbody>
            </table>
        `;

        //SEND to HTML "assembler"
        containerDiv.appendChild(assembler);
    }

    //=== FUNCTION Output the data to the HTML content
    function outputToHTML(data) {
        //=== VARIABLES (quote, stats, earnings, financials)
        var companyName = document.getElementById("companyNameTd");
        var exchange = document.getElementById("exchangeTd");

        var sector = document.getElementById("sectorTd")

        var last = document.getElementById("lastTd");
        var change = document.getElementById("changeTd");
        var changePct = document.getElementById("changePctTd");
        var volume = document.getElementById("volumeTd");
        var mrktCp = document.getElementById("mktCpTd")

        var dividend = document.getElementById("dividendTd");
        var dividendPct = document.getElementById("dividendPctTd");

        //Get JSON data
        var JSONCompanyName = data.MSFT.quote.companyName;
        var JSONExchange = data.MSFT.quote.primaryExchange;
        var JSONLast = data.MSFT.quote.latestPrice;
        var JSONSector = data.MSFT.quote.sector;
        var JSONChange = data.MSFT.quote.change;
        var JSONChangePct = ((data.MSFT.quote.changePercent*100).toFixed(2) + '%')
        var JSONVolume = formatNumber(data.MSFT.quote.latestVolume);
        var JSONMrktCp = ('$'+ formatNumber(data.MSFT.quote.marketCap));

        var JSONDividend = data.MSFT.stats.dividendRate;
        var JSONDividendPct = ((data.MSFT.stats.dividendYield).toFixed(3) + '%');

        //Inject data into HTML 
        companyName.insertAdjacentHTML('beforeend', JSONCompanyName);
        exchange.insertAdjacentHTML('beforeend', JSONExchange);

        sector.innerHTML = JSONSector;

        last.innerHTML = JSONLast;
        change.innerHTML = JSONChange;
        changePct.innerHTML = JSONChangePct;
        volume.innerHTML = JSONVolume;
        mrktCp.innerHTML = JSONMrktCp;

        dividend.innerHTML = JSONDividend;
        dividendPct.innerHTML = JSONDividendPct;
    }

    //=== FUNCTION Format the number to have either M, B, OR T
    function formatNumber(number) {
        if (number === null) return '';

        let value, suffix;
        if (number >= 1e12) {
            value = number / 1e12;
            suffix = 'T';
        } else if (number >= 1e9) {
            value = number / 1e9;
            suffix = 'B';
        } else {
            value = number / 1e6;
            suffix = 'M';
        }

        let digits = value < 10 ? 3 : 0;

        return value.toFixed(digits) + suffix;
    }

</script>

    //=== FUNCTION that creats the table to put into html' 1/2
    function createStockData() {
        //Assemble the whole table here
        let assembler = document.createElement('div');

        assembler.innerHTML = `
            <table class="stock-spec-table" style="width: 100%; background-color: #a1caff;">
                <tbody>
                    <tr>
                        <td>Last</td>
                        <td><b id="lastTd"></b></td>

                        <td>Change</td>
                        <td><b id="changeTd"></b></td>

                        <td>Change %</td>
                        <td><b id="changePctTd"></b></td>

                        <td>Volume</td>
                        <td><b id="volumeTd"></b></td>
                    </tr>

                    <tr>
                        <td>Market Cap</td>
                        <td><b id="mktCpTd"></b></td>

                        <td>Dividend</td>
                        <td><b id="dividendTd"></b></td>

                        <td>Dividend %</td>
                        <td><b id="dividendPctTd"></b></td>
                    </tr>                        

                </tbody>
            </table>
        `;

        //SEND to HTML "assembler"
        containerDiv.appendChild(assembler);
    }

    //=== FUNCTION Output the data to the HTML content
    function outputToHTML(data) {
        //=== VARIABLES (quote, stats, earnings, financials)
        var companyName = document.getElementById("companyNameTd");
        var exchange = document.getElementById("exchangeTd");
        var titleLast = document.getElementById("titleLast");
        var titleChangePct = document.getElementById("titleChangePct");

        var sector = document.getElementById("sectorTd")

        var last = document.getElementById("lastTd");
        var change = document.getElementById("changeTd");
        var changePct = document.getElementById("changePctTd");
        var volume = document.getElementById("volumeTd");
        var mrktCp = document.getElementById("mktCpTd")

        var dividend = document.getElementById("dividendTd");
        var dividendPct = document.getElementById("dividendPctTd");

        //Get JSON data
        var JSONCompanyName = data.MSFT.quote.companyName;
        var JSONExchange = data.MSFT.quote.primaryExchange;
        var JSONLast = data.MSFT.quote.latestPrice;
        var JSONSector = data.MSFT.quote.sector;
        var JSONChange = data.MSFT.quote.change;
        var JSONChangePct = ((data.MSFT.quote.changePercent*100).toFixed(2) + '%')
        var JSONVolume = formatNumber(data.MSFT.quote.latestVolume);
        var JSONMrktCp = ('$'+ formatNumber(data.MSFT.quote.marketCap));

        var JSONDividend = data.MSFT.stats.dividendRate;
        var JSONDividendPct = ((data.MSFT.stats.dividendYield).toFixed(3) + '%');

        //Inject data into HTML 
        companyName.insertAdjacentHTML('beforeend', JSONCompanyName);
        exchange.insertAdjacentHTML('beforeend', JSONExchange);
        last.innerHTML = JSONLast;
        sector.innerHTML = JSONSector;
        titleLast.innerHTML = JSONLast;
        titleChangePct.innerHTML = ('(' + JSONChangePct + ')');
        change.innerHTML = JSONChange;
        changePct.innerHTML = JSONChangePct;
        volume.innerHTML = JSONVolume;
        mrktCp.innerHTML = JSONMrktCp;

        dividend.innerHTML = JSONDividend;
        dividendPct.innerHTML = JSONDividendPct;
    }

    //=== FUNCTION Format the number to have either M, B, OR T
    function formatNumber(number) {
        if (number === null) return '';

        let value, suffix;
        if (number >= 1e12) {
            value = number / 1e12;
            suffix = 'T';
        } else if (number >= 1e9) {
            value = number / 1e9;
            suffix = 'B';
        } else {
            value = number / 1e6;
            suffix = 'M';
        }

        let digits = value < 10 ? 3 : 0;

        return value.toFixed(digits) + suffix;
    }

</script>

0 ответов

Другие вопросы по тегам