Storing the retrieved JSON data in a variable

My current dilemma involves attempting to store JSON data in a variable, but I'm clearly missing something crucial. Initially, I successfully see the JSON displayed in the console as desired. However, upon subsequent attempts to access it later on, all that is returned is a promise. How can I properly save the JSON into a variable so that I can utilize the objects within the JSON at a later time?


var jsondata = fetch(url).then(
    function(u){ return u.json();}
  ).then(
    function(json){
      console.log(json);
    }
  )
console.log(jsondata);

Answer №1

The fetch API is Promise-based and will always result in a new Promise being returned, either resolved or rejected. There are various ways to handle the outcome.

Using Async/Await

async function fetchData(url) {
  const response = await fetch(url);

  return response.json();
}

const data = await fetchData(url);

console.log({ data })

With Callbacks

function fetchData(url, callback) {
  fetch(url)
    .then(response => response.json())
    .then(result => callback(result));
}

fetchData(url, (data) => console.log({ data }))

Answer №2

const jsonDataReturned;    
fetch(url).then(
        function(response){ return response.json();}
      ).then(
        function(data){
          jsonDataReturned = data;
        }
      )

To clarify, the variable jsonDataReturned should be assigned the actual data once the promise is resolved, not the entire promise itself. Make sure you update your code accordingly to avoid any confusion.

Answer №3

To simplify the code, you can create a dedicated function outside the fetch function specifically to handle JSON data. In the example below, the fetch function retrieves the JSON object and then passes it to another function named "data_function." This allows us to easily manipulate and work with the JSON object within the "data_function".

//fetch function
fetch(url).then(
function(u){ return u.json();}
).then(
function(json){
data_function(json); //calling and passing json to another function data_function
}
)

//another functions
function data_function(data){
alert(data.length); 
}

Answer №4

Consider utilizing a callback function as a parameter to avoid exposing variables to the global scope.

function fetchFromAPI(url, callback){
  var data;
  fetch(url)
    .then(res => res.json())
    .then(response => data = response)
    .then(() => callback(data))
 }

fetchFromAPI('https://jsonplaceholder.typicode.com/posts', handleData);

function handleData(arrayOfObjects){
  var results = "";
  arrayOfObjects.forEach( (object) => {
    results += "<p> Id: " + object.id + "<ul>"
    Object.keys(object).forEach( (key) => {
        results += "<li>" + (key + ": " + object[key]) + "</li>";
    });
    results += "</ul> </p> <hr>"
  })
  results += "";
  document.getElementById("myDiv").innerHTML = results;
}

http://jsfiddle.net/5gch2yzw/

Answer №5

One way to incorporate asynchronous functionality into your code is by defining a new async function called getData(). Within this example, data retrieved from a specified URL can be stored in a global variable for further use.

When the getData() function is invoked, it utilizes the fetchData() function to asynchronously retrieve city data from the designated URL. Once the data retrieval process is successful, the information is appended to the citiesData global variable, enabling you to access and utilize this data throughout your script.

async function fetchData(url) {
    const response = await fetch(url);
    const data = await response.json();
    return data;
}

const citiesData = [];
const url = 'https://gist.githubusercontent.com/Miserlou/c5cd8364bf9b2420bb29/raw/2bf258763cdddd704f8ffd3ea9a3e81d25e2c6f6/cities.json';

// Data fetching occurs just once
async function getData() {
    const data = await fetchData(url);
    citiesData.push(...data);
}

getData();

console.log(citiesData);

Answer №6

exploring the latest top-level changes in modules (for nodejs version 18 and above)

let jsonData="";

const fetchJson = async () => {
    const response = await fetch("https://jsonplaceholder.typicode.com/posts/1")
    return await response.json()       
}

jsonData = await fetchJson()
console.log(jsonData.title)//prints: sunt aut facere repellat provident
//console.log(jsonData)

This code snippet is compatible with file.mjs, but not with file.js!

Answer №7

The most straightforward method is to utilize async/await in your code.

To witness the magic, simply enter the following code into your Chrome developer console:

async function getUsers() {
            let response = await fetch('https://api.example.com/users')
            let users = await response.json()
            console.log(users)
    }

getUsers()

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

Parse the JSON object from the request when the content type is set to 'application/x-www-form-urlencoded'

I have an integration with a payment service, and they sent me a request using cURL like this: curl -d '{"merchantAccount":"pipedrive_youscore_rubicon_ltd","orderReference":"WFP-BTN-7181819-635e48482b33d"," ...

Node and Express are correctly logging the response, however the React frontend is logging an entirely different message

Currently, I am in the process of developing a form for an eCommerce platform that allows the administrator/owner to upload images to Cloudinary. At the moment, the image is being successfully uploaded to Cloudinary. Upon logging the response (using conso ...

Is it feasible to set a default value in an HTML input field that is not editable using JavaScript?

Is there a way to set a default value in an input field of HTML that is not editable, and then allow users to add additional text to it? For example, having 'AB' as the default and uneditable starting characters, followed by any numbers such as A ...

``How can one validate a radio button within a reducer by utilizing the event object that is passed into the reducer process

In my React app, I am using the following reducer: const initialState = { genderRadio : false, ageRadio : false } const reducer = (state = initialState, action) => { switch(action.type) { case "VALI_RADIO_INP": console. ...

Setting the borderRadius for a web view on Android Maps V3: A complete guide

In my application, I am using Android Map V3 and have encountered a bug specific to the Kit-Kat version. The chromium kit throws up an error message - nativeOnDraw failed; clearing to background color, which prevents the map from being displayed. Despite ...

Modify the MUI Select icon background color on hover

I have been working on customizing the MUI Select method, and I've encountered difficulty when trying to hover over the "NarrowDownIcon": https://i.sstatic.net/VEZFP.png My goal is to change the hover behavior of this icon by setting its backgroundC ...

Incorporate a minimum height requirement for enabling the scroll to top feature

I am currently dealing with some JavaScript code that scrolls to a specific div when clicked. However, I have encountered an issue where the div is displayed at the very top of the page, causing it to go behind a fixed header that is 90px in height. As a r ...

What is the reason behind the momentary functionality of v-for?

I'm facing a strange issue while working with Vue.js. I'm not sure if the problem lies with my code or if it's a bug in the framework. Here's the scenario: When I use v-for with a comma before it (v-bind), there are no errors but nothi ...

Exploring a JSON object and dynamically populating FormData with values using jquery

I am working with a JSON object in jQuery that looks like this: userObj = { "loginId":"abc123", "class":"5", "email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3f5e5457565311584b4c0e0606087f58525e5653115c5052">[e ...

Ways to retrieve data from response instead of subscription JSON in Angular 2/4

My Service : retrieveData(url,request) { return this.http.post(this.apiUrl+url,request).subscribe( (response) => {return response.json()} ); } My Component : ngOnInit() { this.data = this.dataService.retrieveData(&apos ...

Generate an Android model on-the-fly using a REST client

I recently developed an Android app that includes two tables - one for products and another for items. For example, a product like "wheels" would have items such as wood, rubber, and plastic wheels. However, I've encountered a dilemma where the clien ...

React is unable to locate the component element within the DOM

I'm attempting to set the innerHTML for the div element with the ID of ed. Unfortunately, I am unable to access it once React has finished rendering. It seems that this is due to the render stages, as I am receiving a null value for the div element. W ...

Creating an Image slideShow with only one Image - making it slide on itself

Apologies for this confusing and vague question. Imagine I only have a single image, and I want to create a slideshow using technologies like Angular, jQuery, JavaScript, or just CSS. What I am aiming for is when the user clicks on my slide button, the i ...

Unexpected '->' found on page during loading

After migrating my WordPress site from localhost to the live server, I encountered an issue where "-->" appeared before the page finished loading. Can anyone explain this strange behavior? In addition to this issue, the jQuery scripts I had implemented ...

When you click on the button, the section will not be displayed

I'm facing an issue with my code. I have a set of five buttons and corresponding sections. When a button is clicked, the active and active-btn classes are supposed to be added to that button as well as the corresponding section element with the same i ...

Enhance Bootstrap modals by automatically adjusting the background shadow mask when resizing or changing the content within the modal window

Incorporated within my bootstrap modal window is a form alongside a link that triggers the jQuery functionality of .slideToggle(). By interacting with this link, a concealed div expands. Consequently, the size of the modal popover becomes fluid. Upon click ...

The variable was not able to be assigned any data

Having trouble assigning data to the variable eventsString. I retrieve data from the network using Retrofit within a coroutine, then assign the loaded data to eventsString. However, eventsString still holds the value 12. What am I doing wrong? class Overvi ...

Attempting to use insertAdjacentHTML on a null property results in an error

I keep encountering the same error repeatedly... Can someone please explain what's going wrong here and provide a hint? Error script.js:20 Uncaught TypeError: Cannot read property 'insertAdjacentHTML' of null at renderHTML (script.js:20) a ...

Utilizing the Authorization Header in WebSocket within a React Electron Application

Struggling to establish a connection with a secure websocket that requires Bearer Auth via Header. Despite popular advice, it seems setting headers for WebSockets is not straightforward. How can I achieve this in a React Electron App? Currently using the & ...

Guide to creating completely static HTML using `nuxt generate`?

Looking for a solution to ensure that Vue pages are fully generated as static HTML files in Nuxt even when they are simple and don't require any dynamic data fetching? Let's dig into the issue. <template> <div>hello world</div&g ...