简体   繁体   English

如何在Google Chrome控制台中访问由第三方API检索的JSON数据?

[英]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. 我的网站命中了一个第三方气象API,该API返回如下所示的JSON数据。

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

I'm trying to test some logic I built on Google Chrome Dev Console. 我正在尝试测试我基于Google Chrome开发者控制台构建的一些逻辑。 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. 为了做到这一点,我首先知道如何在控制台中访问JSON数据,但是我不知道该数据的保存位置。 I tried looking into localStorage but I had no luck. 我尝试调查localStorage但没有运气。

Can someone guide me how I can access this JSON data in the Chrome console? 有人可以指导我如何在Chrome控制台中访问此JSON数据吗? Essentially I'm trying to see where this JSON is saved under which object. 本质上,我试图查看此JSON在哪个对象下保存的位置。

Thanks 谢谢

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. 但是您只需复制在网络标签中找到的json数据,然后将其粘贴到开发者工具控制台区域即可。 Just do what you would normally do, like const test = (your pasted JSON) . 只需执行通常的操作即可,例如const test = (your pasted JSON) then you can access it through test.whatever . 那么您可以通过test.whatever访问它。

In the Chrome Dev Tools, go to the Network tab. 在Chrome开发者工具中,转到“网络”标签。 From there you can set it to record all resources downloaded including XMLHttp (AJAX) calls, such as the one to your API. 从那里,您可以对其进行设置,以记录所有下载的资源,包括XMLHttp(AJAX)调用,例如对您的API的调用。

When the JSON response comes back, you will be able to view it here. 当JSON响应返回时,您将可以在此处查看它。 The Preview subtab when you click on the request will contain a "pretty printed" version of the JSON. 单击请求时的“ 预览”子选项卡将包含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. 您还可以查看已发送和接收的标头,重播XHR请求等。

在开发工具中显示广告网络和预览标签。

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 参考: https : //developers.google.com/web/tools/chrome-devtools/network-performance/reference#response

Try this to run this code to your console and save json data variable as data: console.save(data) 尝试将其运行到控制台,并将json数据变量另存为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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在浏览器中访问第三方cookie? - How to access 3rd Party cookies in the Browser? 禁用第三方Cookie和/或网站数据后,Chrome扩展程序无法访问localStorage - Chrome extensions can't access localStorage when 3rd party cookies and/or site data is disabled 无需第三方扩展程序即可永久地在Google Chrome浏览器中执行用户脚本 - Executing Userscripts in Google Chrome permanentely without 3rd party Extension 将循环结构转换为JSON-第三方API - Converting circular structure to JSON - 3rd party API 从Javascript应用程序安全访问第三方API - Secure access to 3rd party API from a Javascript app 从javascript / jQuery中的第三方API序列化数据 - Serialize the data from 3rd party API in javascript/jQuery 使用AngularJS将数据从第三方API保存到CouchDB - Saving data from 3rd party API to CouchDB using AngularJS 如何从第三方API提取数据并使用javascript将其显示在我的页面上? - How do I extract data from a 3rd party api and display it on my page with javascript? 我如何使用websocket使我保持第三方api中的实时数据更新 - How can i use websocket to keep me updated with the live data which is in 3rd party api 如何从第三方库访问角度分量 - How to access angular component from 3rd party library
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM