简体   繁体   English

遍历 node.js 中的 json 文件

[英]iterating through json file in node.js

I'm writing this code to find the long-name of "types" : [ "locality", "political" ] and long-name of "types" : [ "administrative_area_level_2", "political" ] from the json file.我正在编写此代码以从 json 文件中查找"types" : [ "locality", "political" ]的长名称"types" : [ "locality", "political" ]"types" : [ "administrative_area_level_2", "political" ]长名称"types" : [ "administrative_area_level_2", "political" ] but unable to iterate through the array properly但无法正确遍历数组

js file 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;
    }
});

output输出

found
{ long_name: 'Kunustoria',
  short_name: 'Kunustoria',
  types: [ 'locality', 'political' ] }
{ long_name: 'Bardhaman',
  short_name: 'Bardhaman',
  types: [ 'administrative_area_level_2', 'political' ] }
not found

Replace your for loop with this...用这个替换你的 for 循环......

data = JSON.parse(data).results;

data.forEach(function (address) {
  console.log(address['address_components'][0].long_name);
});

First you must install lodash.首先你必须安装lodash。

npm install --save lodash npm install --save lodash

var _ = require('lodash');
var data = api_response_from_google_maps;//Assign the api response here.
var addrs = [];
_.map(data.results, function (address) {
  _.map(address.address_components, function (item) {
    if (_.isEqual(item.types, ["locality", "political"]) || _.isEqual(item.types, ["administrative_area_level_1", "political"])) {
      addrs.push(item);
    }
  })
});

console.log(JSON.stringify(addrs));

This gives an array of objects of adresses_components with types array as you specified.这给出了一个adresses_components的对象数组,其types为您指定的数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM