2016-05-29 2 views
0

私はこのような読書やロギングJSONファイルに問題がある:角2のJSONオブジェクトから必要なデータを読み込むには?

{ 
"results" : [ 
    { 
    "address_components" : [ 
     { 
      "long_name" : "277", 
      "short_name" : "277", 
      "types" : [ "street_number" ] 
     }, 
     { 
      "long_name" : "Bedford Avenue", 
      "short_name" : "Bedford Ave", 
      "types" : [ "route" ] 
     }, 
     { 
      "long_name" : "Williamsburg", 
      "short_name" : "Williamsburg", 
      "types" : [ "neighborhood", "political" ] 
     }, 
     { 
      "long_name" : "Brooklyn", 
      "short_name" : "Brooklyn", 
      "types" : [ "sublocality_level_1", "sublocality", "political" ] 
     }, 
     { 
      "long_name" : "Kings County", 
      "short_name" : "Kings County", 
      "types" : [ "administrative_area_level_2", "political" ] 
     }, 
     { 
      "long_name" : "New York", 
      "short_name" : "NY", 
      "types" : [ "administrative_area_level_1", "political" ] 
     }, 
     { 
      "long_name" : "United States", 
      "short_name" : "US", 
      "types" : [ "country", "political" ] 
     }, 
     { 
      "long_name" : "11211", 
      "short_name" : "11211", 
      "types" : [ "postal_code" ] 
     } 
    ], 
    "formatted_address" : "277 Bedford Ave, Brooklyn, NY 11211, USA", 
    "geometry" : { 
     "location" : { 
      "lat" : 40.714232, 
      "lng" : -73.9612889 
     }, 
     "location_type" : "ROOFTOP", 
     "viewport" : { 
      "northeast" : { 
       "lat" : 40.7155809802915, 
       "lng" : -73.9599399197085 
      }, 
      "southwest" : { 
       "lat" : 40.7128830197085, 
       "lng" : -73.96263788029151 
      } 
     } 
    }, 
    "place_id" : "ChIJd8BlQ2BZwokRAFUEcm_qrcA", 
    "types" : [ "street_address" ] 
    }, 
    ], 
    "status" : "OK" 
    } 

私はこのすべてのデータ、都市の名前をする必要はありません。どのように私はちょうどオブジェクト行を望んでログに記録できます

私はこのコードを試してみましたが、私がしたいようにそれは動作しません:あなたの例のデータについては

Object.keys(JSON[0]); 
+0

http://stackoverflow.com/questions/6359995/get-city-from-geocoder-results – maksbd19

+0

は、あなたが "277ベッドフォードアベニュー、ブルックリン、NY 11211、USA" または単に "ブルックリン" したいですか? –

+0

あなたのデータにはどのような制約がありますか? – Dinesh

答えて

1

sublocality_level_1でフィルタリングして再実行することができます同じようなJSONがソートされている場合は、それを使用してください。

const getCity = data => data.address_components 
     .filter(x => x.types && x.types.indexOf("sublocality_level_1") > -1) 
     .map(x => x.long_name)[0]; 

//Get a city name from only the first result 
const oneCity = getCity(jsonData.results[0]); 

//Get an array with all cities (for all the results) 
const allCities = jsonData.results.map(getCity); 
1

>> data['results'][0]['address_components'][2]['long_name'] 
Williamsburg 

>> data['results'][0]['address_components'][3]['long_name'] 
Brooklyn 

あなたはJSON文字列としてデータを取得する場合、あなたはそれを変換する必要があります前のJavaScriptオブジェクトへ

data = JSON.parse(the_json_string_here); 
関連する問題