A simple guide to fetching JSON data and storing it in a variable, then parsing it and displaying it

I am looking to retrieve JSON data from the Yahoo Finance API, store it in a JavaScript variable, extract specific information such as "name" and "price", and then display it in an HTML table.

The JSON data can be accessed via the following link:

Currently, I am unsure about how to load the data into a variable, but once I figure that out, my goal is to parse the relevant information and showcase it in an organized manner on a web page.

Answer №1

Using only JavaScript:

If you try to access the WebService URL using XMLHttpRequest, you may encounter CORS issues:

XMLHttpRequest cannot load . No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

However, there is a workaround using the service.

In this case, you would request: "". This can be easily implemented in JavaScript without the need for jQuery.

A demonstration has been prepared showcasing how to achieve this:

This demonstrates:

(function() {
  var newXHR;

  // Function to make XMLHttpRequest calls without relying on jQuery or AngularJS $http service.
  function sendXHR(options) {
    //       (Modern browsers)    OR (Internet Explorer 5 or 6).
    newXHR = new XMLHttpRequest() || new ActiveXObject("Microsoft.XMLHTTP");
    if (options.sendJSON === true) {
      options.contentType = "application/json; charset=utf-8";
      options.data = JSON.stringify(options.data);
    } else {
      options.contentType = "application/x-www-form-urlencoded";
    }
    newXHR.open(options.type, options.url, options.async || true);
    newXHR.setRequestHeader("Content-Type", options.contentType);
    newXHR.send((options.type == "POST") ? options.data : null);
    newXHR.onreadystatechange = options.callback; 
    return newXHR;
  }

  // Making a call to the WebService utilizing the helper function.
  sendXHR({
    type: "GET",
    url: "https://crossorigin.me/http://finance.yahoo.com/webservice/v1/symbols/%5EIXIC/quote?format=json&view=detail",
    callback: function() {
      if (newXHR.readyState === 4 && newXHR.status === 200) {
        var data = JSON.parse(newXHR.response);

        var table = document.getElementById("table");

        var html = "<table><thead>";
        html += "<th>Name</th><th>Price</th>";
        html += "</thead>";
        html += "<tbody>";
        for (i = 0; i < data.list.resources.length; i++) {
          html += "<tr><td>" + data.list.resources[i].resource.fields.name + "</td><td>" + data.list.resources[i].resource.fields.price + "</td></tr>";
        }
        html += "</tbody></table>";
        table.innerHTML = html;
      }
    }
  });
})();
#table table {
  border: solid 1px #CCCCCC;
  border-collapse: collapse;
}
#table table td {
  border: solid 1px #CCCCCC;
  padding: 5px;
}
<div id="table"></div>

For a shorter version of this solution, view the following link:

https://jsfiddle.net/dannyjhonston/9okhpebk/

Answer №2

To properly process JSON in javascript, you can utilize the JSON.parse(strinfied_json) method.

After parsing, the JSON is converted into a standard javascript object that can be accessed using either the [] or . syntax.

Check out this illustration:

var data = "{
  person: {
    name: \"John Doe\",
    age: 30,
    city: \"New York\"
  }
}"

var parsedData = JSON.parse(data)

// Accessing properties of the object
var name = parsedData["person"]["name"];
var age = parsedData["person"]["age"];

$('#name_display').text(name);
$('#age_display').text(age);

Answer №3

If you need to fetch JSON data from a URL and store it in a JavaScript variable, you can utilize the jQuery getJSON method. This method allows you to load JSON data from a specified URL. In the example below, the function displayHtml is used to handle the retrieved data:

var jqxhr = $.getJSON( "http://finance.yahoo.com/webservice/v1/symbols/%5EIXIC/quote?format=json&view=detail", displayHtml)
      .fail(function() {
        alert("Failed to retrieve data from:  http://finance.yahoo.com/webservice/v1/symbols/%5EIXIC/quote?format=json&view=detail")
      });

Answer №4

Thank you for your response. I am having trouble implementing your example with the code provided below. The initial alert is triggered, but nothing seems to work after the .getjson function. I assume that once it is functioning properly, the URL will be loaded into displayHTML for parsing?

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Demo</title>
</head>
<body>
<a href="http://jquery.com/">jQuery</a>
 <script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>

<script>
alert("initiating");
var jqxhr = $.getJSON( "http://finance.yahoo.com/webservice/v1/symbols/%5EIXIC/quote?format=json&view=detail", displayHtml)
  .fail(function() {
    alert("no response from:  http://finance.yahoo.com/webservice/v1/symbols/%5EIXIC/quote?format=json&view=detail")
  });

alert("completed");

</script>
</body>
</html>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

ReactJS incorporates multiple CSS files

I am currently working on developing a Single Page Application using ReactJS. However, I am facing an issue with styling. Currently, I have created 3 different pages (with the intention of adding more in the future), each having its own CSS file that is im ...

What is the best way to send a parameter to a mousewheel event?

for (var i = 0; i < 10; i++) { $('#content-scroll' + i).mousewheel(function(event, delta) { if (delta > 0) sliderUp(i - 1); else if (delta < 0) sliderDown(i - 1); return false; // prevent default }); } I am facing an iss ...

Cross-Platform: Varied functionalities in disabled input fields (avoiding any direct replication)

My input HTML field is disabled, but I've noticed that in some browsers (such as Chrome, Edge, Internet Explorer, and Opera), it's still possible to select and copy the text. However, in Firefox, this functionality does not work. To test this yo ...

Tips on manually refreshing AngularJS view using ControllerAs syntax?

As I work on creating a user-friendly dashboard with widgets that can be sorted, docked, and floated, I encountered an issue. The controls I am using generate floating widgets as HTML at the bottom of the DOM, outside the controller scope where they were c ...

Retrieve the specific day of the previous complete week within a designated month using JavaScript

Is there a way to determine the last full week of any given month? For example, I need to find the Wednesday of the last full week in April each year. Here is the desired output: April 24, 2019, April 22, 2020, April 28, 2021, April 27, 2022, and so on. v ...

Utilizing AngularJS to implement checkbox selection within a table

I'm working on a method that will receive an Id from a table when a checkbox is checked and update the $scope.selected array in my Angular controller. If the checkbox is unchecked, it should remove the corresponding item from $scope.selected. Here&ap ...

Choosing a nested object within a JavaScript object

Is there a way to select the style contents of an object within another object? The data consists of a json encoded array. In my scenario, I am using data[i].replies and getting 2. How can I access data[i].userstyles instead? It seems to be an object. h ...

Testing inherit from a parent class in a unit test for Angular 2

Trying to create a unit test that checks if the method from the base class is being called This is the base class: export abstract class Animal{ protected eatFood() { console.log("EAT FOOD!") } } Here is the class under test: export ...

Is it commonplace for redux to generate an abundance of storage?

I'm noticing a lot of lines in the terminal, is it really necessary to create so many storage instances? 4. The WrappedApp just created a new store with withRedux(MyApp) { initialState: undefined, initialStateFromGSPorGSSR: undefined } 14:47:39.619 ...

Avoid including newline characters in the string returned from a curl response

I'm facing some challenges in grasping the concept of avoiding interpolation of escape characters in strings, especially those retrieved from a curl response. The data I am receiving looks like this: {"foo":"bar\r\nbaz"} When executing cur ...

The absence of the dark class in the body is still allowing the impactful influence of Tailwind

I set up a ThemeContext in my NextJS project to switch between light and dark themes on my website. However, I encountered an issue where elements that have the "dark:" prefix in their class names apply the dark theme instead of the initial light theme whe ...

Extracting data from a webpage's dynamic table using Python with Selenium and

I am planning to extract the data from the JavaScript tables found in the following link: import codecs import lxml.html as lh from lxml import etree import requests from selenium import webdriver import urllib2 from bs4 import BeautifulSoup URL = &apo ...

Shifting Angular Component Declarations to a New Location

Here's a question that might sound silly: In my Angular project, I am looking to reorganize my component declarations by moving them from angular.module.ts to modules/modules.modules.ts. The goal is to structure my src/app directory as follows: src ...

Ascending with Progress Indicator Slider

After successfully creating a Bootstrap 5 Carousel with an automated count for each slide (limited to 4) and a corresponding progress bar, I encountered an issue with getting the previous button to function correctly. While clicking the next button works s ...

Display all the names of the files from various file inputs in a unified notification

I have developed a function that checks if the selected file names already exist in the database. It currently alerts a message for each file name found in the database, which can be overwhelming with multiple files. I am looking for suggestions on how t ...

Recursion using Node.js Promises

I'm facing some difficulties while iterating through my Promises and completing my parser code: let startFrom = 0, totalRecords = 10000, doneRecords = 0 const rows = 10 const parserRequests = function () { if (startFrom <= totalRecords) { ...

Ways to terminate a looping function in jquery

My latest project involves creating a function that loops through a set of divs, fading in and out the next one. The challenge I'm facing is figuring out how to stop this loop upon either a click event, an if/else condition, or focus. After some resea ...

The word "yargs" will not activate a command within a script

I have a NodeJs script that requires parsing command line arguments. Here is the code I have written: import yargs from "yargs"; import { hideBin } from 'yargs/helpers'; //.... yargs(hideBin(process.argv)).command('--add-item ...

Can an onload function be triggered within the location.href command?

Can a function be called onload in the location.href using jQuery? location.href = getContextPath() + "/home/returnSeachResult?search=" + $('#id-search-text-box').val() + "&category=" + $('#search_concept').text() + "onload='j ...

Arranging HTML components in Vue.js using v-for loop

Recently, I started using vue.js and I have a requirement where I need to display an HTML structure based on API data. The structure should look like this: <div class="row"> <div><p>text1</p><img src="{{imgurl1}}" /></di ...