我正在通过Wundground的API以JSON格式获取天气数据,没有遇到任何问题。我正在尝试将该数据存储在MongoDB中供以后使用。实际上,我可以获取数据并将其写入Mongo中的集合。但是,当我执行db.collection.find()时,它几乎看起来像每个单独的字符被分别保存而不是以JSON格式保存。这里是获取数据并应该保存到Mongo的代码片段:
我需要在将数据保存到Mongo之前解析它吗?那么我错过了什么。正如我所说,如果我将所有天气数据输出到控制台,所有数据都会完美地显示出来,我只是在Node.JS和MongoDB之间做错了什么。
// Define the Wunderground method.
var method = "/api/" + apiKey + "/conditions/q/" + state + "/" + city + ".json";
// Define the HTTP post properties.
var options = {
host: 'api.wunderground.com',
path: method,
method: 'GET',
port: 80
};
// Create the HTTP POST.
var request = http.request(options, function (response) {
var str = '';
// Create the listener for data being returned.
response.on('data', function (chunk) {
str += chunk;
// Create the listener for the end of the POST.
response.on('end', function (){
db.collection('weathercollection').save(str, function(err, records) {
if (err) throw err;
console.log("record added");
});
});
以下是JSON格式的天气数据的小节选:
{ "current_observation": {
"image": {
"url": "http://icons-ak.com/graphics/logo.png",
"title": "Weather Underground"
},
"display_location": {
"full":"My City, State",
"city":"My City",
我需要在将数据保存到Mongo之前解析它吗?那么我错过了什么。正如我所说,如果我将所有天气数据输出到控制台,所有数据都会完美地显示出来,我只是在Node.JS和MongoDB之间做错了什么。
谢谢。
更新***
我尝试以这种方式解析"str"
// Create the listener for data being returned.
response.on('data', function (chunk) {
str += chunk;
var jsonResult = JSON.parse(str);
// Create the listener for the end of the POST.
response.on('end', function (){
db.collection('weathercollection').save(jsonResult, function(err, records) {
if (err) throw err;
console.log("record added");`
似乎那也行不通。我会再次查看它。