我已经编写了将JSON写入文件并下载的代码。除无法将出现在浏览器和控制台中的JSON数据写入文件外,其他所有文件均显示良好。 JSON数据(dataStr)在下载的文件中显示为未定义。 这是代码的摘录:
function exportToJsonFile(obj) {
let dataStr = JSON.stringify(obj); // Converts object into string
console.log('dataStr type: '+ typeof dataStr); // String
console.log(dataStr); // Data appears in console
$('#dataStr').text(dataStr); // Data appears in browser
let text = 'JSON data: '+ dataStr; // 'text' is written to file but dataStr cannot be written to file
console.log('text type: '+ typeof text); // String
let dataUri = 'data:application/json;charset=utf-8,'+ encodeURIComponent(text); // write to file
let exportFileDefaultName = 'raingeojson.json'; // set default file name
let linkElement = document.createElement('a'); // create link element
linkElement.setAttribute('href', dataUri); // create href = dataUri
linkElement.setAttribute('download', exportFileDefaultName); // create link of the download to the button
linkElement.click(); // create click
}
编辑:这是将值传递给obj的函数。
$.getJSON("https://api.data.gov.sg/v1/environment/rainfall?date=2019-07-03",
rainfall = function(data_rainfall){
console.log(data_rainfall);
var apiGeoLoc = { type: "FeatureCollection", features: []};
apiGeo = { type: "FeatureCollection", features: []};
for (var i in data_rainfall.items){
for (var j in data_rainfall.items[i].readings){
var date_t = data_rainfall.items[i].timestamp.split('T');
var date = date_t[0];
var time = date_t[1].split(':');
var hour_string = time[0];
var hour = parseInt(hour_string);
apiGeo.features.push({
"type":"Feature",
"properties": {
"timestamp": data_rainfall.items[i].timestamp,
"date": date,
"Hour": hour,
"id": data_rainfall.items[i].readings[j].station_id,
"value": data_rainfall.items[i].readings[j].value
},
"geometry":{}
});
}}
for (var i in data_rainfall.metadata.stations){
apiGeoLoc.features.push({
"type":"Feature",
"properties": {
"station_name": data_rainfall.metadata.stations[i].name,
"id": data_rainfall.metadata.stations[i].id
},
"geometry":{
"type": "Point",
"coordinates": [data_rainfall.metadata.stations[i].location.longitude, data_rainfall.metadata.stations[i].location.latitude]
}
});
}
for(var a in apiGeo.features){
for (var b in apiGeoLoc.features){
if (apiGeo.features[a].properties.id===apiGeoLoc.features[b].properties.id){
for(var attr in apiGeoLoc.features[b].properties){ //create new attribute to insert properties
apiGeo.features[a].properties[attr] = apiGeoLoc.features[b].properties[attr]; //apiGeo takes apiGeoLoc attributes
}
for(var coord in apiGeoLoc.features[b].geometry){
apiGeo.features[a].geometry[coord] = apiGeoLoc.features[b].geometry[coord]; //apiGeo takes apiGeoLoc coordinates
}
}
}}
console.log(apiGeo);
apiGeof = apiGeo.features;
exportToJsonFile(apiGeof);
});