从url中收集数百个json文件,并用JavaScript组合成一个json文档



我正试图1(从该网站检索数百个独立的json文件https://bioguide.congress.gov/它包含美国的立法者,2(处理它们,3(将它们组合成一个包含所有单个记录的大json。

我正在处理的一些文件(每个立法者都有一个不同的url,以json文件格式包含他们的数据(可以在以下url中找到:

https://bioguide.congress.gov/search/bio/F000061.json
https://bioguide.congress.gov/search/bio/F000062.json
https://bioguide.congress.gov/search/bio/F000063.json
https://bioguide.congress.gov/search/bio/F000064.json
https://bioguide.congress.gov/search/bio/F000091.json
https://bioguide.congress.gov/search/bio/F000092.json

我的方法是创建一个for循环,在不同的id上循环,并将所有记录组合到一个对象数组中。不幸的是,我在尝试访问数据时遇到了问题。

到目前为止,我已经尝试了以下方法,但我得到了一个CORS错误。

使用fetch:

url = "https://bioguide.congress.gov/search/bio/F000061.json"
fetch(url)
.then((res) => res.text())
.then((text) => {
console.log(text);
})
.catch((err) => console.log(err));

在获取中使用无cors模式并获得空响应:

url = "https://bioguide.congress.gov/search/bio/F000061.json"
const data = await fetch(url, { mode: "no-cors" })

使用d3:

url = "https://bioguide.congress.gov/search/bio/F000061.json"
const data = d3.json(url);

我收到了一个与CORS相关的错误blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

如果能就这一问题提出任何建议和建议,我将不胜感激。谢谢

根据@code在他们的回答中所说的,这里有一个经过设计(但经过测试(的NodeJS示例,它每秒从服务器获取一次数据范围(60-69(,并将其编译为一个JSON文件。

import express from 'express';
import fetch from 'node-fetch';
import { writeFile } from 'fs/promises';
const app = express();
const port = process.env.PORT || 4000;
let dataset;
let dataLoadComplete;
app.listen(port, () => {
console.log(`Server running on port ${port}`);
});

function getData() {
return new Promise((res, rej) => {
// Initialise the data array
let arr = [];
dataLoadComplete = false;
// Initialise the page number
async function loop(page = 0) {
try {
// Use the incremented page number in the url 
const uri = `https://bioguide.congress.gov/search/bio/F00006${page}.json`;
// Get the data, parse it, and add it to the
// array we set up to capture all of the data
const response = await fetch(uri);
const data = await response.json();
arr = [ ...arr, data];
console.log(`Loading page: ${page}`);
// Call the function again to get the next
// set of data if we've not reached the end of the range,
// or return the finalised data in the promise response 
if (page < 10) {
setTimeout(loop, 1000, ++page);
} else {
console.log('API calls complete');
res(arr);
}
} catch (err) {
rej(err);
}
}
loop();
});
}
// Call the looping function and, once complete,
// write the JSON to a file
async function main() {
const completed = await getData();
dataset = completed;
dataLoadComplete = true;
writeFile('data.json', JSON.stringify(dataset, null, 2), 'utf8');
}
main();

好吧,您收到了一个CORS(跨源资源共享(错误,因为您向其发送AJAX请求的网站(bioguide.congression.gov(没有明确启用CORS,这意味着由于安全原因,您无法向该网站发送AJAX要求(客户端(。

如果要向该站点发送请求,必须从服务器端(如PHP、Node、Python等(发送请求。

更多关于主题

最新更新