如何从 JavaScript 中的 URL 获取 JSON?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12460378/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get JSON from URL in JavaScript?
提问by Yi?it Do?u? ?z?elik
This URLreturns JSON:
此 URL返回 JSON:
{
query: {
count: 1,
created: "2015-12-09T17:12:09Z",
lang: "en-US",
diagnostics: {},
...
}
}
I tried this, and it didn't work:
我试过这个,但没有用:
responseObj = readJsonFromUrl('http://query.yahooapis.com/v1/publ...');
var count = responseObj.query.count;
console.log(count) // should be 1
How can I get a JavaScript object from this URL's JSON response?
如何从此 URL 的 JSON 响应中获取 JavaScript 对象?
采纳答案by Dan Barzilay
You can use jQuery .getJSON()
function:
您可以使用 jQuery.getJSON()
函数:
$.getJSON('http://query.yahooapis.com/v1/public/yql?q=select%20%2a%20from%20yahoo.finance.quotes%20WHERE%20symbol%3D%27WRC%27&format=json&diagnostics=true&env=store://datatables.org/alltableswithkeys&callback', function(data) {
//data is the JSON string
});
If you don't want to use jQuery you should look at this answer for pure JS solution: https://stackoverflow.com/a/2499647/1361042
如果你不想使用 jQuery,你应该看看这个纯 JS 解决方案的答案:https: //stackoverflow.com/a/2499647/1361042
回答by Robin Hartmann
If you want to do it in plain javascript, you can define a function like this:
如果你想用普通的 javascript 来做,你可以定义一个这样的函数:
var getJSON = function(url, callback) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'json';
xhr.onload = function() {
var status = xhr.status;
if (status === 200) {
callback(null, xhr.response);
} else {
callback(status, xhr.response);
}
};
xhr.send();
};
And use it like this:
并像这样使用它:
getJSON('http://query.yahooapis.com/v1/public/yql?q=select%20%2a%20from%20yahoo.finance.quotes%20WHERE%20symbol%3D%27WRC%27&format=json&diagnostics=true&env=store://datatables.org/alltableswithkeys&callback',
function(err, data) {
if (err !== null) {
alert('Something went wrong: ' + err);
} else {
alert('Your query count: ' + data.query.count);
}
});
Note that data
is an object, so you can access its attributes without having to parse it.
请注意,这data
是一个对象,因此您可以访问其属性而无需解析它。
回答by DBrown
With Chrome, Firefox, Safari, Edge, and Webview you can natively use the fetch API which makes this a lot easier, and much more terse.
借助 Chrome、Firefox、Safari、Edge 和 Webview,您可以在本机使用 fetch API,这使这变得更容易,也更简洁。
If you need support for IE or older browsers, you can also use the fetch polyfill.
如果您需要支持 IE 或更旧的浏览器,您还可以使用fetch polyfill。
let url = 'https://example.com';
fetch(url)
.then(res => res.json())
.then((out) => {
console.log('Checkout this JSON! ', out);
})
.catch(err => { throw err });
Even though Node.js does not have this method built-in, you can use node-fetchwhich allows for the exact same implementation.
即使 Node.js 没有内置此方法,您也可以使用node-fetch来实现完全相同的实现。
回答by Kamil Kie?czewski
ES8(2017) try
ES8(2017) 尝试
obj = await (await fetch(url)).json();
async function load() {
let url = 'https://my-json-server.typicode.com/typicode/demo/db';
let obj = await (await fetch(url)).json();
console.log(obj);
}
load();
you can handle errors by try-catch
你可以通过 try-catch 处理错误
async function load() {
let url = 'http://query.yahooapis.com/v1/publ...';
let obj = null;
try {
obj = await (await fetch(url)).json();
} catch(e) {
console.log('error');
}
console.log(obj);
}
load();
回答by Emile Bergeron
Axiosis a promise based HTTP client for the browser and node.js.
Axios是用于浏览器和 node.js 的基于Promise的 HTTP 客户端。
It offers automatic transforms for JSON data and it's the official recommendation from the Vue.js teamwhen migrating from the 1.0 version which included a REST client by default.
它为 JSON 数据提供自动转换,这是Vue.js 团队在从默认包含 REST 客户端的 1.0 版本迁移时的官方建议。
Performing a
GET
request// Make a request for a user with a given ID axios.get('http://query.yahooapis.com/v1/publ...') .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); });
执行
GET
请求// Make a request for a user with a given ID axios.get('http://query.yahooapis.com/v1/publ...') .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); });
Or even just axios(url)
is enough as a GET
request is the default.
或者甚至就axios(url)
足够了,因为GET
请求是默认的。
回答by Dan Alboteanu
Define a function like:
定义一个函数,如:
fetchRestaurants(callback) {
fetch(`http://www.restaurants.com`)
.then(response => response.json())
.then(json => callback(null, json.restaurants))
.catch(error => callback(error, null))
}
Then use it like this:
然后像这样使用它:
fetchRestaurants((error, restaurants) => {
if (error)
console.log(error)
else
console.log(restaurants[0])
});
回答by Shivansh Srivastava
You can access JSON data by using fetch() in JavaScript
您可以在 JavaScript 中使用 fetch() 访问 JSON 数据
Update url parameter of fetch() with your url.
使用您的 url 更新 fetch() 的 url 参数。
fetch(url)
.then(function(response){
return response.json();
})
.then(function(data){
console.log(data);
})
Hope It helps, it worked perfectly for me.
希望它有帮助,它对我来说非常有效。
回答by zq-jhon
async function fetchDataAsync() {
const response = await fetch('paste URL');
console.log(await response.json())
}
fetchDataAsync();
回答by ashish bandiwar
//Resolved
const fetchPromise1 = fetch(url);
fetchPromise1.then(response => {
console.log(response);
});
//Pending
const fetchPromise = fetch(url);
console.log(fetchPromise);