Show only specific data from JSON results

I am trying to display a specific cryptocurrency's price without the need for curly braces or explicitly stating "USD". Currently, it appears as {"USD":0.4823} when using the following code:

<script>
        $(document).ready(function () {
                $.getJSON('https://min-api.cryptocompare.com/data/price?fsym=XLM&tsyms=USD',
                function (data) {
                    document.write(JSON.stringify(data));
                });
        });
    </script>

I am having difficulty progressing from this point and have not been able to find relevant solutions in similar questions' answers.

Answer №1

Avoid using stringify when you need to avoid a string representation of the complete object.

Instead, access the values of the object's properties directly.

document.write(data.USD);

Answer №2

If you're solely interested in the price 0.4823 of the item { "USD":0.4823 }, regardless of whether the currency is "USD," "EUR," or any other, the solutions provided below will always display only the price and disregard the currency.

Solution 1: Utilize pure Javascript without JQuery

document.addEventListener("DOMContentLoaded", function(event) { 
  fetch('https://min-api.cryptocompare.com/data/price?fsym=XLM&tsyms=USD')
  .then(x => x.json())
  .then(data => {
    const key = Object.keys(data)[0]; // first key, in this case it's USD
    document.write(data[key]);
  
  });
});

Solution 2: With JQuery, utilize promises

$(document).ready(function () {
  $.getJSON('https://min-api.cryptocompare.com/data/price?fsym=XLM&tsyms=USD')
    .done(data => {
      const key = Object.keys(data)[0]; // first key, in this case it's USD
      document.write(data[key]);
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

It is recommended to use Solution 1 as it purely relies on Javascript for implementation!

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 appearance of the circle in Safari is rough and lacks smoothness

My circle animation works perfectly on Google Chrome, but when I switch to Safari the edges appear faded and blurry. I tried adding "webkit" to fix it, but had no luck. Is there a compatibility issue with Safari and CSS animations? Here is my code: Snapsh ...

Detect the "@" character through keyUp for the implementation of @mentions feature

I am currently working on implementing an @mention feature using Vue and Vanilla JS, but I am facing issues with targeting the "@" character specifically. Within my template: <trix-editor ref="trix" @keyup="listenForUser" ></trix-editor& ...

Is there a way to emphasize a particular day on the calendar obtained from the URL?

I have implemented FullCalendar functionality to enable users to select a specific date, retrieve data from a database, and then reload the page with that data. The page is updated with the selected date in the URL. However, when the page reloads, althoug ...

Unraveling the mystery: How does JavaScript interpret the colon?

I have a quick question: When I type abc:xyz:123 in my GoogleChrome browser console, it evaluates to 123. How does JavaScript interpret the : symbol in this scenario? ...

Stuck autoplay feature when clicking

There is an issue with the play function in the built-in browser audio player. Initially, it starts automatically with the following code... function play(){ var audio = document.getElementById("myaudio"); audio.play(); } However, when modifying the code ...

create a JavaScript array variable for posting items

My goal is to use this javascript to make four posts for the 'var msg' array. However, it currently posts 'encodeURIComponent(msg[i])' four times instead. How can I resolve this issue? var msg = ['one', 'two& ...

Error: The variable "weather" is not defined while using React with the weatherbit API

I'm currently developing a React application that utilizes the Weatherbit API. However, I have encountered an issue with the weather object when calling my data array. Below is the code snippet where the problem occurs: import React from "react&q ...

Another inquiry regarding a city autocomplete field in a global setting

While I understand that this question may have been previously asked, I have spent several days searching without finding a satisfactory answer. Some websites, such as eventful.com, etc., have an autosuggest city field with cities from all over the world ...

There was an error in the function involving the addition operation, as it did not have a loop with the appropriate signature for the specified data types

Currently, I'm using great-expectation for testing my pipeline. I have a Dataframe batch of type: great_expectations.dataset.pandas_dataset.PandasDataset My goal is to create a dynamic validation expression. For example, batch.("columnname","value" ...

What is the best way to append a key to a JSON list in Python for an object with matching name?

Hey there, I'm facing an issue and I could really use some help: I have a project where I'm retrieving a JSON file through a request and creating a list with the specific keys. Here's how it looks: { "name":"Lucas White&qu ...

The browser is preventing a cross origin request in Fetch

Currently, I am utilizing node, express, and react to build a sign-in portal. In the frontend, I have created app.js and signin.js files. The partial code snippet in the signin.js file looks like this: onSubmitSignIn = () => { fetch("http://localhost:3 ...

A clever method for implementing lazy-loading using mobx

Can you provide guidance on the most effective way to lazy load properties with MobX? I've been grappling with this issue for a few days now, and I've struggled to find suitable examples ever since strict mode was introduced. While I appreciate ...

Adjustable annotations in flot chart

When creating a flot, I can draw segments by specifying the markings in the options. markings: [ { xaxis: { from: 150, to: 200 }, color: "#ff8888" }, { xaxis: { from: 500, to: 750 }, color: "#ff8888" } ] Now, I am looking to remove these existing m ...

Generating dynamic div elements using jQuery

I am currently working on developing a button that will automatically generate pre-formatted divs each time it is clicked. The divs consist of forms with fields that should already be populated with data stored in JavaScript variables. Example: <d ...

Exploring the versatility of Grails 3 profiles through JSON rendering and implementing a One to Many relationship with

I am currently utilizing gson and web profile in my project. The domain I am working with is: package json import grails.rest.* @Resource(readOnly = false, formats = ['json', 'xml']) class Hero { String name String data S ...

Searching for corresponding items in multi-dimensional arrays using Javascript

For my project in Javascript, I am facing the challenge of matching entire arrays. In this scenario, I have a userInput array and my goal is to locate a similar array within a multi-dimensional array and display the match. var t1 = [0,0,0]; var t2 = [1,0, ...

Unexpected value detected in D3 for translate function, refusing to accept variable

I'm experiencing a peculiar issue with D3 where it refuses to accept my JSON data when referenced by a variable, but oddly enough, if I print the data to the console and manually paste it back into the same variable, it works perfectly fine. The foll ...

Implementing optimal techniques to create a JavaScript file for data retrieval in a Node.js application

I've developed a file specifically for data access purposes, where I'm keeping all my functions: const sql = require('mssql'); async function getUsers(config) { try { let pool = await sql.connect(conf ...

Generate a random number using the Math.random() method in Node.js/JavaScript to access a folder on the local machine

I am facing a challenge in reading a JSON file located deep within multiple folders on my local machine. The issue arises because the folder name where the file is stored changes every time, as it is generated using the Math.random() method with the prefix ...

Turn off the scrolling bars and only allow scrolling using the mouse wheel or touch scrolling

Is there a way to only enable scrolling through a webpage using the mouse wheel or touch scrolling on mobile devices, while disabling browser scroll bars? This would allow users to navigate up and down through div elements. Here is the concept: HTML: &l ...