Reputation: 1481
I have a problem in reading and logging JSON file like this:
{
"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"
}
I just need the name of city, not all of this data. How could I log just wanted object row.
I tried this code but that doesn't work like I want:
Object.keys(JSON[0]);
Upvotes: 0
Views: 760
Reputation: 5929
You can filter by sublocality_level_1
and do it in a function to reuse it if you receive a similar JSON sorted different.
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);
Upvotes: 1
Reputation: 12558
For your example data
>> data['results'][0]['address_components'][2]['long_name']
Williamsburg
>> data['results'][0]['address_components'][3]['long_name']
Brooklyn
If you get the data as JSON string, you need to convert it to a JavaScript objects before
data = JSON.parse(the_json_string_here);
Upvotes: 1