What is the best way to extract a string from a JSON object array?

I'm encountering an issue retrieving any of the strings from the JSON data provided by the Google Finance API. When debugging, I keep getting "undefined." In the example below, my main focus is on extracting the symbol (t) and the current price (l).

 $.getJSON("http://finance.google.com/finance/info?client=ig&q=TSLA&callback=?",
        function(json) {
        var Stocks = json;
        var text ="";   
        text = Stocks.l + " represents the current stock price for: " + Stocks.t;
        document.getElementById('Textn').innerHTML = text; 

        });

Answer №1

The reason Stocks.l is undefined is because the response you receive is an array, not a single object.

If you happen to get an array with multiple objects, using a loop would be helpful - even if there's only one element in the array, the loop won't cause any issues. The following code utilizes es6 object destructuring, which may not work in all browsers currently:

$.getJSON("https://finance.google.com/finance/info?client=ig&q=TSLA&callback=?", json => {
  for (let {l, t} of json) {
    let text = l + " is the current stock price for: " + t;
    document.getElementById('Textn').innerHTML += text;
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><div id="Textn">

</div>

A version with es5 syntax would look something like this:

$.getJSON("https://finance.google.com/finance/info?client=ig&q=TSLA&callback=?", function(json) {
  json.forEach(function(v) {
    var text = v.l + " is the current stock price for: " + v.t;
    document.getElementById('Textn').innerHTML += text;
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="Textn">

</div>

Answer №2

The data provided consists of an array containing multiple objects:

[
  {
    "order_id": "20675439",
    "product" : "iPhone",
    "price" : "$999"
    //and so on

To access specific properties of an object, you must first navigate through the array to locate the desired element:

data[0].product //retrieves the value of property "product" from the object at index 0 in the array, resulting in "iPhone"

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

Unable to process despite clicking button (no error messages)

I'm in the process of setting up an options page for my very first extension. As a beginner in coding, I might have made some rookie mistakes along the way. However, I am facing challenges with basic functionality that was previously working seamlessl ...

Track the loading times of individual web pages using JavaScript

Users have been reporting that my existing single-page web application is not performing well, but unfortunately I can't change the code. To address this issue, I want to track the loading time in the following manner: Record the timestamp of when a ...

Discrepancy in Gson behavior between generated APK and debug mode

My current task involves parsing data received from a notification bundle: String intervalsData = data.getString(ARG_INTERVAL, "[]"); Type intervalListType = new TypeToken<List<Interval>>() {}.getType(); List<Interval> intervalList = Con ...

Code executing twice instead of once in Javascript

Having trouble with a script in my demo below. When I enter "first input", submit, then click on the returned "first input", it alerts once as intended. However, upon refresh, if I enter "first input", submit, then add "second input", submit, and finally c ...

Altering the appearance of a different element with React

I'm new to using react and struggling to make a Component appear when I click on a button. Here's an example of the code I have so far: <Button>GO</Button> <CalendarIcon id="calendar visibility="hidden"/> and th ...

Implementing jquery document.ready() with <img onload> event

My current need is to trigger a JavaScript function each time an image loads on the page, but I also require that the DOM of the page is fully loaded before the script executes. I have provided a sample example below and would appreciate feedback on wheth ...

Alternative to dynamic arrays in Javascript

I successfully implemented a masonry grid using Flexbox. Initially, the items were ordered vertically, so I developed a function to rearrange them horizontally: Original Order: 1 4 7 2 5 8 3 6 9 New Order (with my sorting function): 1 2 3 4 5 6 7 8 9 ...

What is a Brief Illustration of the Jackson Scala Extension?

Is there a straightforward example available for utilizing Jackson serialization and deserialization with the Scala module for version 2.10? I am specifically interested in achieving JSON conversion using reflection without needing to annotate or assign fi ...

Having trouble loading HTML content from another file

Here is the code snippet in question: <script> var load = function load_home(){ document.getElementById("content").innerHTML='<object type="type/html" data="/linker/templates/button.html" ></object>'; } </script> ...

Issues occurring with setting the variable using the Google latlng API

I've tried searching for solutions on various forums, including stackoverflow, but haven't been able to make it work. The issue lies in this code snippet where the variable 'pos' is not being set: var geocoder= new google.maps.Geocoder ...

Changing CSS classes with each click of the user, using Jquery

Looking for a way to seamlessly switch between two links with different CSS classes each time a user clicks? Here's what's currently happening: <a class="class1" id="class1">Class1</a> <a class="class2" id="class2">Class2</a ...

A guide on verifying a username and password via URL using JavaScript

As I work on developing a hybrid application using the Intel XDK tool and jQuery Mobile framework for the user interface, one of my current tasks is implementing a login function. This function involves simply inputting a username and password and clicking ...

Tips for real-time editing a class or functional component in Storybook

Hey there, I am currently utilizing the storybook/react library to generate stories of my components. Everything has been going smoothly so far. I have followed the guide on https://www.learnstorybook.com/react/en/get-started and added stories on the left ...

Validating date and time picker pairs using JavaScript

I am looking to implement start and end date validation using datetimepicker. My current code is not functioning as expected. I need the end date to be greater than or equal to the start date, and vice versa. If anyone has a solution for this issue, plea ...

Decoding into identical structure with distinct JSON identifier

I have encountered a situation where I need to manipulate JSON data by performing certain transformations and then send it by marshaling. However, my requirement is to change the variable name in the final marshaled JSON. Is it possible to marshal the dat ...

Is it possible to utilize an API response within a conditional statement in NextJS?

I am working on a change password feature that interacts with an API for verification. If the current password entered is incorrect, I want to display an error message. If you have any suggestions on how to proceed or if there are any flaws in my approach ...

Tips for improving the readability of my code

This code snippet pertains to handling a POST request in Express.js with MongoDB integration. router.post('/', function(req, res){ var data = req.body; Tag.find({name: data.name}).limit(1).exec( function(err, result){ if(err) { // ...

Implementing Default Language in Next.js 14 for Static Export without URL Prefix: A Step-by-Step Guide

Currently, I am in the process of developing a website using Next.js 14, with the intention of exporting it as a static site for distribution through a CDN (Cloudflare Pages). The website I am working on requires support for internationalization (i18n) to ...

How to eliminate a specific portion of a string within a string using PHP

After retrieving a string from Google API search result snippets, I encountered an issue with the presence of <b> and </b> tags within the string. This posed a problem for further processing, so I needed to remove these tags. The original code ...

What sets cross-fetch apart from isomorphic-fetch?

According to the Redux documentation, cross-fetch is the preferred choice, whereas most other sources recommend using isomorphic-fetch. What sets these two apart? ...