What is the best way to choose a specific JSON element?

Seeking information from an API, my goal is to extract specific data using JavaScript selectors. I am specifically interested in two objects from the JSON below:

[
  {
    "symbol": {
      "tickerSymbol": "@CH20",
      "vendor": "DTN",
      "marketName": "cbot",
      "symbol": "@C@1",
      "description": "CORN March 2020"
    },
    "last": {
      "number": 380.25
    },
    "high": {
      "number": 382.75
    },
    "low": {
      "number": 379.5
    },
    "open": {
      "number": 382.25
    },
    "bid": {
      "number": 380
    },
    "ask": {
      "number": 380.25
    },
    "close": null,
    "previous": {
      "number": 383
    },
    "cumVolume": 80553,
    "openInterest": 428574,
    "change": {
      "number": -2.75
    },
    "week52High": null,
    "week52Low": null,
    "month": "Mar 20",
    "settleDate": "2020-02-12",
    "settlePrice": {
      "number": 383
    },
    "expirationDate": "2020-03-13",
    "contractHigh": {
      "number": 476
    },
    "contractLow": {
      "number": 365.75
    },
    "quoteDelay": 10,
    "bidDateTime": "2020-02-13T10:40:12-06:00",
    "askDateTime": "2020-02-13T10:40:12-06:00",
    "tradeDateTime": "2020-02-13T10:39:31-06:00"
   }
]

The following code snippet demonstrates how I am utilizing JSON.parse:

var data = JSON.parse(this.response)

     if (request.status >= 200 && request.status < 400)
     {

         var last = data.last.number
         var change = data.change.number


         console.log(last);
         console.log(change);
         console.log(data);


     }

Answer №1

Start by accessing the array position in the response data.

In this example, use this.response[0]. From there, you can target a specific key in the JSON.

var last = response[0].last.number
var change = response[0].change.number

console.log({last}); // displays: last: 380.25
console.log({change}); // shows: change: -2.75

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

Converting a multi-dimensional array in PHP to JSON through an SQL request

Hey there, I'm facing a problem similar to my previous question on Stack Overflow about converting SQL requests into JSON. Despite it seeming quite simple, I haven't been able to find a solution yet. My SQL table structure is very basic: $sql=" ...

recognizing individuals when a particular action is taken or when there is a disruption

Just starting to explore node.js I currently have a PHP/Laravel cms alongside a basic Nodejs game server that generates numbers in a loop To connect my PHP backend with Nodejs, I utilize Socketio and employ Socketio-JWT for user identification On the cl ...

Having trouble with my basic AJAX request; it's not functioning as expected

I am currently diving into the world of Ajax and I've hit a roadblock: 1. HTML : <body> <form> Username: <input type="text" id="username" name="username"/> <input type="submit" id="submit" /> </form> <scrip ...

How can I execute JavaScript code within Aptana Studio 3 IDE?

After creating a Test.js file, I added two lines of JavaScript code: var x = 5; console.log("The answer is: " + x); The desired output would be: "The answer is: 5" I am curious if there's a way to view this outcome in the Aptana Scripting console, ...

Using regex in Javascript to find and match an ID within a string

JavaScript: var data='<div id="hai">this is div</div>'; I am looking to retrieve only the ID "hai" using a regular expression in JavaScript. The expected output should be, var id = regularexpression(data); The variable id should n ...

"Encountering a bug with Angular-bootstrap pagination displaying an undefined function

Attempting to implement angular-bootstrap pagination footer Encountering an error TypeError: undefined is not a function at Object.fn (http://localhost:3000/lib/angular-bootstrap/ui-bootstrap-tpls.js:2265:5) at Scope.$get.Scope.$digest (http://l ...

Error Arises When React Components Are Nested within Objects

I'm encountering a peculiar issue with my component. It works perfectly fine when retrieving data from State at a high level, but as soon as I try to access nested objects, it throws an error: "TypeError: Cannot read property 'name' of undef ...

Setting up a software from a GitHub source

My issue arises when attempting to install a particular package of mine with the version specified as a specific git branch. The problem occurs because the repository does not contain the dist folder, which is required by my npm package. Here is the metho ...

What is the syntax for accessing an element within an array in a function?

This code snippet retrieves an array of users stored in a Firestore database. Each document in the collection corresponds to a user and has a unique ID. const [user] = useAuthState(auth); const [userData, setUserData] = useState([]); const usersColl ...

CSS file not loading in an ExpressJS application

I'm facing an issue with my ExpressJS web app where only the HTML files are loading but the CSS rules are not being applied. I have linked the HTML file with the CSS file and also included express.static(path.join(__dirname, 'css')) in my ap ...

Failure to read the response will cause the HttpUrlConnection request to malfunction

I have been attempting to send a json request using HttpUrlConnection in Java. Despite following multiple examples, I am unable to successfully add data to the server as there is no response. Below is the code I am currently using: URL url = new URL(u ...

What is the best way to parse a JSON file in Angular?

Can you please explain how to read a JSON file? I have been able to successfully read a JSON file using a controller, but when I try to read it from a factory, the content is null. Why is this happening? http://plnkr.co/edit/THdlp00GuSk1NS6rqe5k?p=preview ...

Implementing Interactive Buttons

As a newcomer to JScript, I have been attempting to dynamically add textboxes and select menus to a form. While I have managed to make them appear on the page, I am facing an issue with JQuery not functioning properly. Although the textboxes are visible on ...

When attempting to call a bundle file using browserify from React, an unexpected character '�' Syntax error is thrown: react_app_testing/src/HashBundle.js: Unexpected character '�' (1:0

Hey there, I'm currently struggling with an unexpected unicode character issue. Let me provide some context: I've created a simple class called HashFunction.js that hashes a string: var crypto = require('crypto') module.exports=class H ...

Tips for making jQuery DataTables switch between multiple DOM tables?

I am working on a project where I need to display different jQuery Datatables based on the selected option in a <select> element. The data for each Datatable is stored in hidden DOM <table> elements: <!-- Make sure jquery.dataTables.css and ...

What is the best way to integrate PHP code into my countdown JavaScript code to automatically insert data into a MySQL column once the countdown has reached

I have created a countdown JavaScript code that resets every day at 23:00 of local time. I am wondering if it is possible to incorporate PHP code into this script so that after the countdown finishes each day, it automatically adds "5" to my "Credit" col ...

What could be causing me to receive an undefined result when attempting to retrieve a specific element?

Why am I receiving 'undefined' for my ID? I am currently working on a NextJS app and attempting to create a route to retrieve a specific element by its ID. Below is the code for my route: const { events } = require('../../../db.json') ...

The world of visual content and data interchange: AS3 graphics

Prior to this, I inquired about action script 3 Json request However, my main query is centered around transforming an image into a JSON object. Any suggestions? Thanks! ...

Refreshing the page to display new data after clicking the update button

function update(){ var name= document.getElementById("TextBox").value; $.ajax({ url: '....', type: 'post', ...

Calculating the position of an element in an array passed from a separate file with ReactJS and Ant Design

I'm currently working with a file that contains some JavaScript code featuring an array with multiple objects containing key-value pairs. In my main file (App.jsx), I initialize a State Variable and assign it the array from another JS file. My goal no ...