Home > database >  Using Fetch to get an API response, using JSON.stringify(), and then...?
Using Fetch to get an API response, using JSON.stringify(), and then...?

Time:05-22

I have searched this nine ways from Sunday, but there's something I'm missing here, and I don't know what it is.

I'm using fetch to grab some data from Mapbox:

var response = fetch(myURL)

.then(response => response.json())
.then (data => console.log(JSON.stringify(data)))

When I run this and look at the console, I can see that I have indeed grabbed the data, because it gets logged. (I'm putting what got logged at the end because it's a lot.)

The problem is I don't know how to get the information into a format where I can work with it. All I want is the lat/long, but I can't work out how to get it. I tried pushing the stringified data into an array, I tried writing an function that assigned the stringified data to a variable, and I'm not getting it.

It's probably something really obvious that I'm missing. If you could unblind me I'd sure appreciate it.

Here's what shows up in the console log.

"type":"FeatureCollection","query":["1600","pennsylvania","avenue","washington","dc"],"features":[{"id":"address.1048737153875776","type":"Feature","place_type":["address"],"relevance":0.90963,"properties":{"accuracy":"rooftop"},"text":"Pennsylvania Avenue Southeast","place_name":"1600 Pennsylvania Avenue Southeast, Washington, District of Columbia 20003, United States","matching_place_name":"1600 Pennsylvania Avenue Southeast, Washington, DC 20003, United States","center":[-76.982015,38.879235],"geometry":{"type":"Point","coordinates":[-76.982015,38.879235]},"address":"1600","context":[{"id":"neighborhood.2918372884011750","text":"Capitol Hill"},{"id":"postcode.12587193810898840","text":"20003"},{"id":"place.2915387490246050","wikidata":"Q61","text":"Washington"},{"id":"region.14064402149979320","short_code":"US-DC","wikidata":"Q3551781","text":"District of Columbia"},{"id":"country.14135384517372290","wikidata":"Q30","short_code":"us","text":"United States"}]}],"attribution":"NOTICE: © 2022 Mapbox and its suppliers. All rights reserved. Use of this data is subject to the Mapbox Terms of Service (https://www.mapbox.com/about/maps/). This response and the information it contains may not be retained. POI(s) provided by Foursquare."}

CodePudding user response:

data is an object. And assuming you want the lat/lng information in the coordinates array you can navigate it like this.

const data={type:"FeatureCollection",query:["1600","pennsylvania","avenue","washington","dc"],features:[{id:"address.1048737153875776",type:"Feature",place_type:["address"],relevance:.90963,properties:{accuracy:"rooftop"},text:"Pennsylvania Avenue Southeast",place_name:"1600 Pennsylvania Avenue Southeast, Washington, District of Columbia 20003, United States",matching_place_name:"1600 Pennsylvania Avenue Southeast, Washington, DC 20003, United States",center:[-76.982015,38.879235],geometry:{type:"Point",coordinates:[-76.982015,38.879235]},address:"1600",context:[{id:"neighborhood.2918372884011750",text:"Capitol Hill"},{id:"postcode.12587193810898840",text:"20003"},{id:"place.2915387490246050",wikidata:"Q61",text:"Washington"},{id:"region.14064402149979320",short_code:"US-DC",wikidata:"Q3551781",text:"District of Columbia"},{id:"country.14135384517372290",wikidata:"Q30",short_code:"us",text:"United States"}]}]};

// Access the first element of the `features` array and
// find the `geometry` property. Destructure the `coordinates`
// property (also and array) from it.
const { coordinates } = data.features[0].geometry;

// And then destructure the `lat/lng` values from
// that array
const [lat, lng] = coordinates;

console.log(lat, lng);

Additional documentation

CodePudding user response:

The response.json() is a JavaScript object. So something like this should work for you. I'm just logging to the console here, but you could save the data to a database via an ajax call or dynamically create a html table to view the details.

var response = fetch(myURL)
    .then(response => {
        responseObject = response.json();
        let features = responseObject.features;        
        for (let i = 0; i < features.length; i  )
        {
            let coords = responseObject.features[i].geometry.coordinates;
            console.log(`${features.id} Lat = ${coords[0]} Long = ${coords[1]}`);
        }
    });
  • Related