在一个函数中获取多个 JSON 文件
Posted
技术标签:
【中文标题】在一个函数中获取多个 JSON 文件【英文标题】:Get several JSON files in one function 【发布时间】:2017-03-02 09:32:10 【问题描述】:JSON链接的结构如下:
www.something.com/link-number-rest-of-the-link.com.json
现在我需要获取几个 JSON 链接文件,唯一改变的是上面链接中的 number 部分。假设它的范围从 10 到 40,所以第一个看起来像这样:
www.something.com/link-10-rest-of-the-link.json
第二个看起来像这样
www.something.com/link-11-rest-of-the-link.com.json
以此类推,直到达到第 40 位。
有没有一种方法可以让我在一个函数中获得所有内容。我试过这个:
var nmr = function(for(nmr=10;nmr<40;nmr++));
var json = 'www.something.com/link'+nmr+'rest-of-the-link.json';
但它不会工作。
有没有办法做到这一点?
请注意,我没有放“http”部分,因为 SO 会自动链接它。
谢谢。
【问题讨论】:
是的,您可以在一个对象中聚合多个调用的结果:对于给定范围的每个数字,进行调用并将响应添加到您将返回的数组中 你如何神奇地直接从 url 中获取 json? 请提供样品。谢谢。 @madalin,已编辑。 @tholo 你编辑了什么,你的 ajax 请求在哪里? 【参考方案1】:概念
生成承诺数组,将从 url 调用每个 json 文件
同时执行每个承诺
样本
const Promise = require('bluebird')
const rp = require('request-promise')
function getJsonFromUrlParam(num)
const uri = `www.something.com/link-$num-rest-of-the-link.json`
return rp( method: 'GET', uri, json: true )
/** declare param */
const params = []
for (let i = 10; i <= 40; i++)
/** get each promise param */
params.push(getJsonFromUrlParam(i))
/** get each json file in the same time */
Promise.all(params)
.then(result =>
/** get result here
* result is array of json files
*/
console.log(result)
)
【讨论】:
我们如何在 v1 中做到这一点?【参考方案2】:这样试试,
var json = [];
for(var i = 10; i <= 40; i++)
json.push('www.something.com/link-'+i+'-rest-of-the-link.json');
现在json
将拥有从 10 到 40 的所有链接。如果您想获取内容,请使用 ajax
来完成
【讨论】:
【参考方案3】:你可以像这样构建数组
var links = [];
for(var i=2005;i<2015.length;i++)
links.push('http://www.link.com/an-'+i+'-rest');
//now make your request for each link
另一个例子
var requested = 0;
function startLoading()
if(requested==2015)
return alert("all files loaded");
makeRequest('http://www.link.com/an-'+requested+'-rest');
function makeRequest(url)
//the body of request
//then
//if response is ready make what you want for it and go next
requested++;
startLoading();
// and startLoading(); to go to the next link
startLoading(); //start
【讨论】:
以上是关于在一个函数中获取多个 JSON 文件的主要内容,如果未能解决你的问题,请参考以下文章
如何在网站 json api 中获取第一个 json 文件?