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

Triggering a new window on button click with Vue and Nuxt

Having an issue with a button click event in Vue that opens a PDF using window.open(). It's working well on all browsers except for Safari on MAC. Any ideas what could be causing this? Should I pass $event to the method? <div class="button-do ...

Can you help me streamline the code for the Sign Up Form app using React and jQuery?

Hi everyone, this marks my debut post on StackOverflow as I embark on the journey to become a full stack developer. To enhance my skills, I've been using FrontEnd Mentor for practice and managed to solve a challenge with the code provided below. Any s ...

Creating a function within a module that takes in a relative file path in NodeJs

Currently, I am working on creating a function similar to NodeJS require. With this function, you can call require("./your-file") and the file ./your-file will be understood as a sibling of the calling module, eliminating the need to specify the full path. ...

How to access iFrame in ReactJS using document.getElementById

I am facing a challenge on my website where I need to transfer data (using postMessage) to an iframe. Typically in plain JavaScript, I would use techniques like document.getElementById or $("#iframe") in jQuery to target the iframe. However, I am unsure ...

When working with Java, it is important to remember that a JSONObject text always needs to start with a '{' at the first character

I've been struggling to troubleshoot a JAXB JSON issue, but I can't seem to pinpoint the source of the problem. The error message I'm receiving states: Caused by: org.codehaus.jettison.json.JSONException: A JSONObject text must begin with & ...

Tips for interpreting JSON content within a C# HttpPost function

I need assistance with extracting data from a JSON body and then displaying it in an HttpPost method using C#. The JSON payload includes: { "name": "John", "age": "20" } [HttpPost] public async Task<IAct ...

What is the best approach to slowly transition a value to a different one over a set period of time?

if(!isWalking) { isWalking = true; var animation = setInterval(function () {$player.css({'left': "+="+boxSize/25})}, 10); setTimeout(function(){clearInterval(animation)},250); setTimeout(function(){isWalking = false},250); ...

Aurora MySQL causes PHP to stumble when encoding data into JSON

After transitioning my application from MySQL to Amazon Aurora's MySQL service, I encountered a challenge. The data retrieved from the database was used to search an Elasticsearch index through PHP's Elasticsearch library, which encodes query dat ...

Is there a way to deactivate middleware in Node, Express, and Mocha?

My application features a hello world app structured as follows: let clientAuthMiddleware = () => (req, res, next) => { if (!req.client.authorized) { return res.status(401).send('Invalid client certificate authentication.'); } ret ...

What is the reason for sending a single file to the server?

A function called "import File" was developed to send multiple files to the server, but only one file is being received. Input: <input type="files" id="files" name="files" multiple onChange={ (e) => this.importFile(e.target.files) } ...

The problem of removing issue divs persists despite Jquery's efforts

Just yesterday, I successfully created a Commentbox using PHP, HTML, and ajax. The beauty of the ajax part is that it allows me to delete a comment without having to refresh the page. To achieve this, I assign a unique id to each comment (div) through the ...

Where do I find the resultant value following the completion of a video production through editly?

Hey there, I have a quick question... I was following the instructions in the README for editly, and I successfully created videos by calling editly like this: // creating video editly(editSpec) .catch(console.error); The only issue is that I am using Ex ...

Asynchronous JavaScript function within a loop fails to refresh the document object model (DOM) despite

I have been working on a function that utilizes ajax to retrieve instructions from a backend server while the page is loading. The ajax code I've written retrieves the instructions based on the number provided and displays them using the response.setT ...

Creating an automatic image carousel using a combination of Jquery, Javascript, and CSS

I have been working on creating a slider using jQuery and javascript, but I am facing some issues with the autoplay functionality and the next-previous buttons. This slider is intended for displaying images as a title indicates. Can anyone assist me with i ...

Tips for managing blur events to execute personalized logic within Formik

I am currently delving into the world of React/Next.js, Formik, and Yup. My goal is to make an API call to the database upon blurring out of an input field. This call will fetch some data, perform database-level validation, and populate the next input fiel ...

JavaScript code failing to return array contents

As I navigate through the realms of NodeJS application development handling .nessus result files, I encounter an intriguing behavior quandary when generating an array of numbers. The primary goal is to create an array [1234,1223,1222] from a "results" file ...

There are no leaks displayed in Chrome Dev Tools, however, the Task Manager will show them until Chrome eventually crashes

Do you have a CPU-intensive application that you're working on? Check it out here: https://codepen.io/team/amcharts/pen/47c41af971fe467b8b41f29be7ed1880 It involves a Canvas on which various elements are constantly being drawn. Here's the HTML ...

How to use expressjs to fetch an image from a URL and show it on a webpage

I am currently running an image API from my home server, and I am working on creating a cloud-hosted page that will retrieve the image in the backend and display it, adding a layer of abstraction. My goal is to achieve the following: index.js var express ...

What is the best way to trigger a unique modal dialog for every element that is clicked on?

I simply want to click on the state and have that state's specific pop-up appear. $("path, circle").on('click', function(e) { $('#info-box').css('display', 'block'); $('#info-box').html($(this ...

Iterate through an array to extract specific objects and exclude them from another array

Within my code, I have an array named allItems that stores objects. allItems = [ { id: 1, name: 'item1' }, { id: 2, name: 'item2' }, { id: 3, name: 'item3' } ] I am seeking a way to filter out the objects from th ...