我正在編寫此代碼以從json文件中找到"types" : [ "locality", "political" ]
的長名稱和"types" : [ "administrative_area_level_2", "political" ]
的長名稱。但無法通過數組迭代正確遍歷node.js中的json文件
JS文件
var request = require('request');
request('http://maps.googleapis.com/maps/api/geocode/json?latlng=23.6519148,87.13857650000001', function(error, response, data) {
if (!(!error && response.statusCode == 200)) {
console.log('error! ');
return;
}
data = JSON.parse(data);
for (var i in data.results) {
for (var j in data.results[i]) {
if (j == 'address_components') {
console.log('found')
console.log(data.results[i][j][1]);
console.log(data.results[i][j][2]);
for (var k in data.results[i]){
if(k == 'long_name')
console.log('found')
}
console.log('not found')
}
}
break;
}
});
輸出
found
{ long_name: 'Kunustoria',
short_name: 'Kunustoria',
types: [ 'locality', 'political' ] }
{ long_name: 'Bardhaman',
short_name: 'Bardhaman',
types: [ 'administrative_area_level_2', 'political' ] }
not found
作爲輸出需要什麼? –
long_name「types」:[「locality」,「political」]和long_name的「types」:[「administrative_area_level_2」,「political」] .....即「Kunustoria」和「Bardhaman」 – Ankit
。一旦你執行這一行'data = JSON.parse(data);'你不再處理JSON,而是處理一個普通的JavaScript對象。 –