user7418039
user7418039

Reputation: 311

How to access JSON data retrieved by 3rd party API in Google Chrome Console?

My website hits a 3rd party weather API which returns JSON data like below.

{
"locations": "NYC", 
"temperature":"100"
...
}

I'm trying to test some logic I built on Google Chrome Dev Console. In order to do that, I first know how to access the JSON data in the console but I can't figure out where this data is saved. I tried looking into localStorage but I had no luck.

Can someone guide me how I can access this JSON data in the Chrome console? Essentially I'm trying to see where this JSON is saved under which object.

Thanks

Upvotes: 1

Views: 2911

Answers (3)

Trung Hoang
Trung Hoang

Reputation: 13

Try this to run this code to your console and save json data variable as data: console.save(data)

(function(console){

    console.save = function(data, filename){

        console.log('data is '+data);
        if(!data) {
            console.error('Console.save: No data')
            return;
        }

        if(!filename) filename = 'console'

        if(typeof data === "object"){
            data = JSON.stringify(data, undefined, 4)
        }

        var blob = new Blob([data], {type: 'text/json'}),
            e    = document.createEvent('MouseEvents'),
            a    = document.createElement('a')

        a.download = filename+ '.json'
        a.href = window.URL.createObjectURL(blob)
        a.dataset.downloadurl =  ['text/json', a.download, a.href].join(':')
        e.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null)
        a.dispatchEvent(e)
    }
})(console)

Upvotes: 1

Jeremy Harris
Jeremy Harris

Reputation: 24549

In the Chrome Dev Tools, go to the Network tab. From there you can set it to record all resources downloaded including XMLHttp (AJAX) calls, such as the one to your API.

When the JSON response comes back, you will be able to view it here. The Preview subtab when you click on the request will contain a "pretty printed" version of the JSON. The Response subtab will contain the raw response. You can also view the headers that were sent and received, replay the XHR request, etc.

Showing the network and preview tabs in dev tools.

Here is a functioning example of how you might explore the data in the console by adding it to the global namespace. Please remember to remove this from your code in production as it is bad practice to pollute the global namespace. Other than that, have fun! The developer tools are one of the sharpest knives in a web developer's arsenal.

var startTime = new Date().getTime();

// Create temporary global
writeLog('Creating temp global variable', 'msg-info');
var myData = null;

// Fetch options
writeLog('Defining fetch options', 'msg-info');
let options = {
  method: 'GET'
};

// Make AJAX call. When complete, the temporary global will
// be populated with your JSON data.
writeLog('Making AJAX fetch call', 'msg-info');
fetch('https://jsonplaceholder.typicode.com/todos/1', options)
  .then(function(response) {
    if (!response.ok) {
      writeLog('HTTP ERROR RECEIVED:' + response.status, 'msg-error');
      throw new Error('HTTP error, status = ' + response.status);
    }
    writeLog('JSON Response received', 'msg-info');
    return response.json();
  })
  .then(function(jsonData) {
    writeLog('Assigning JSON to global variable', 'msg-info');
    window.myData = jsonData;
    writeLog('Call Successful! Data ready to be accessed in Chrome Dev Console!', 'msg-success');
    document.getElementById("rawData").innerHTML = JSON.stringify(jsonData, undefined, 2);
  });

// Logging function
function writeLog(msg, className) {
  var node = document.createElement('li');
  if (className.length > 0) {
    node.className = className;
  }
  var currentTime = new Date().getTime();
  var elapsedTime = currentTime - startTime;
  var textNode = document.createTextNode(msg + ' [' + elapsedTime + ' ms]');
  node.appendChild(textNode);
  document.getElementById('log').appendChild(node);
  startTime = currentTime;
}
code {
  color: green;
  font-weight: bold;
  border: 1px solid green;
  padding: 3px;
}

h4 {
  border-bottom: 1px solid #AAA;
  background-color: #333;
  padding: 5px;
  color: #FFF;
  margin-top: 10px;
}

#log li {
  font-weight: bold;
}

.msg-info {
  color: #007cff;
}

.msg-error {
  color: red;
}

.msg-success {
  color: green;
}

#rawData {
  color: red !important;
}
<html>

<body>
  <h2>Client Side API Call Test</h2>
  <h3>When the call returns, you may use the developer console to interact with the response stored in a global variable <code>myData</code></h3>
  <h4>LIVE REQUEST LOG:</h4>
  <ul id="log"></ul>
  <h4>RAW DATA PREVIEW:</h4>
  <pre id="rawData"></pre>
  <h4>EXAMPLE CHROME CONSOLE USAGE</h4>
  Try typing this in the console after the carat symbol: <code>myData.title</code>. Or you can just type <code>myData</code> to see the whole JSON object.
  <br><br>
</body>

</html>

Reference: https://developers.google.com/web/tools/chrome-devtools/network-performance/reference#response

Upvotes: 0

asapon
asapon

Reputation: 69

Rep is too low so I can't comment on the other answer.

But you can just copy the json data you find in the network tab and paste it into the developer tool console area. Just do what you would normally do, like const test = (your pasted JSON). then you can access it through test.whatever.

Upvotes: 2

Related Questions