Accessing a value in JSON (beginner level)

Hello everyone! I have come across a URL: . My goal now is to extract the value (Price) of a specified key (name).

I am aware that there have been similar inquiries in the past, but unfortunately, I haven't been able to make it work as JSON is relatively new to me.

If possible, I would like to achieve this using javascript.

I am counting on your assistance!

While browsing through other questions, I stumbled upon something like this, but couldn't quite get it to function properly:

var accessJSON = function(url, callback) {
    var xhr = new XMLHttpRequest();
    xhr.open('get', url, true);
    xhr.responseType = 'json';
    xhr.onload = function() {
      var status = xhr.status;
      if (status == 200) {
        callback(null, xhr.response);
      } else {
        callback(status);
      }
    };
    xhr.send();
};

accessJSON('https://www.googleapis.com/freebase/v1/text/en/bob_dylan', function(err, data) {
  if (err != null) {
    alert('Oops, an error occurred: ' + err);
  } else {
    alert('Here is your Json result:  ' + data.result);
    result.innerText = data.result;
  }
});

At present, the code I am working with looks like this:

accessJSON('https://api.csgofast.com/price/all', function(err, data) {
  if (err != null) {
    console.log("There was an issue retrieving pricing information!");
  } else {
    console.log("Item price : " + data['Sticker | Good Game']);

  }
});

Answer №1

Can you clarify what you mean by "not functioning"? The alert is appearing on the screen.

Web Browser

The issue may be that the variable result has not been defined yet. If you have:

<div id="result"></div>

then ensure to use

var result = document.getElementById('result');

before attempting to modify its innerText.

You can view a live demo here.

For Node.js

If you are executing this script in Node.js, keep in mind that HTTP requests need to be handled differently. Below is the necessary code snippet.

var https = require('https');

var getJSON = function(url, callback) {
  https.get(url, function (response) {
    var buffer = '';
    response.on('error', callback);
    response.on('data', function (d) { buffer += d; });
    response.on('end', function () {
      callback(null, JSON.parse(buffer));
    });
  });
};

getJSON('https://api.csgofast.com/price/all', function(err, data) {
  if (err) {
    console.log('An error occurred: ' + err);
  } else {
    console.log('Item price: ' + data['Sticker | Good Game']);
  }
});

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

The catch-all route handler is triggered following a response being sent by a designated route handler

Currently, I am facing a peculiar issue with the routing on my Express-based server while trying to implement authentication. Here's a snippet of code that highlights the problem: app.get('/', function (req, res) { console.log('thi ...

Steps for returning a res.send(req.body) upon sending back to a function

I'm currently working on sending the req.body from a POST request route back to the executing function for further processing. The structure of req.body is as follows: { username: 'aa', password: 'ss' } After making the post requ ...

What is the best method for ensuring that my JavaScript tracking script has been properly installed on the customer's website?

We provide a SAAS analytics application that functions similarly to Hotjar and Google Analytics. To track user data, our customers must integrate our JavaScript code into their websites. How can we confirm if the script has been successfully integrated in ...

Parsing Json in AWS with Gson Library

Currently I am extracting pricing data from the http://aws.amazon.com/ec2/pricing/pricing-ebs-optimized-instances.json. Here is an example of the code to retrieve it: public class SampleJson { @SuppressWarnings("unchecked") public static void main(String ...

Unable to connect to React Node Socket.IO application from any source other than localhost using IPv4 and NGROK

I recently followed a tutorial on creating a simple React app/Node with Socket.IO. The tutorial worked perfectly, so I decided to test it with two other devices: One PC on the same wifi network (via IPv4 - 192.168.1.8:3000) A mobile device using Ngrok tun ...

Stop the occurrence of numerous ajax requests being triggered by clicking

Having an issue with handling multiple ajax requests. In my scenario, there is a form with a button that triggers a service upon clicking it. This service is responsible for loading a list of items into a table, but currently it only loads one item at a ti ...

Strategies for transferring data from index.html to component.ts in Angular 4

Greetings, as a newcomer to Angular, I am seeking advice on how to link my Index.html file to component.ts. Please review the code snippet below where I have created a function called scannerOutput in my Angular index.html file which is functioning properl ...

No acknowledgment from command

Why doesn't the bot respond when I run this command? There are no errors. Do I have the role that matches in r.id? client.on('message', async message => { // Check if the user has a role with an id if(message.author.bot) return; ...

Unable to implement multiple draggable inner objects using Angular 5 and dragula library

After struggling for the past few days, I can't seem to get it to work... Here is a brief explanation of my issue: In this example, I have an array of objects structured like this: public containers: Array<object> = [ { "name": "contain ...

Using Codeigniter to fetch a PHP array in an AJAX success callback

I have implemented a jQuery script to send the value selected from a dropdown menu to my controller. The controller then calls a function in my model to execute a query using this value, and retrieve an array of results from the database. These results are ...

Encountering a 404 error when trying to click on 'allow' after using Firebase Cloud Messaging, and attempting to add a service worker manually proves unsuccessful in resolving the issue

Currently, I am working on integrating FCM (Firebase Cloud Messaging) into a React app. Initially, I tested it on a simple project without React and everything worked smoothly. However, implementing it in the React app has presented some challenges for me. ...

Pause the event listener temporarily and reattach it after specific actions have been completed

I am currently working on a React app that includes a scrollable div. Here is an example: <main id="main" onScroll={this.handleScroll}> My question is, how can I temporarily remove the onScroll event listener from the main element and then reattach ...

Tips on resolving the Hydration error in localStorage while using Next.js

Having issues persisting context using localStorage in a Next.js project, resulting in hydration error upon page refresh. Any ideas on how to resolve this issue? type AppState = { name: string; salary: number; info: { email: string; departme ...

Searching for a property in JSON using C# can be done by parsing the

Ensuring that every request in our ASP.Net Web API project is logged is a priority. Each request requires a search for a specific property/token (PersonId) within the payload, which must then be stored in the log table. The challenge arises from the fact ...

Maintain query parameters in Angular6 while routing with canActivate

When using Auth guard to verify login status and redirecting to the login page if a user is not logged in, there seems to be an issue with losing all query parameters during the redirection process. I attempted to preserve the query params by adding { qu ...

Step-by-step guide on how to showcase elements within v-for by clicking on them

In my data array, only the first element is visible by default. Clicking on either the YES or NO button will display the element with the corresponding id of yes_section or no_section (depending on which button was clicked). For instance, if we click on ...

Deploying a React App to Github Pages Results in a Blank Screen

After successfully uploading a simple react app onto GitHub pages using gh-pages, I attempted to import the Shards dashboard project (https://github.com/DesignRevision/shards-dashboard-react) onto my GitHub page. Unfortunately, all I see is a blank page. ...

Guide to converting a log string into JSON using Javascript

I encountered a console log that appears as follows: 2021-01-06T09:06:05.541212726Z D saveGarment: Function execution took 736 ms, finished with status code: 204 2021-01-06T09:06:10.844901031Z D saveGarment: Function execution started 2021-01-06T09:06:16.1 ...

What is the best way to insert hyperlinks within every cell of a table using Angular?

I am currently working on a table created with ng-repeat in Angular. The cells are populated by variables in the scope. <tbody> <tr ng-repeat="item in items" myDirective> <td>{{item.title}}</td> <td>{{item.field}}&l ...

Downloading the file from the specified URL is taking too much time when using the save as blob function

I have developed a service to retrieve and save files from a specified URL. (function() { angular.module('SOME_APP') .service("downloadService", downloadService); function downloadService($http){ var downloadFil ...