hey guys hey going my name is DOM and
today I want to demonstrate how to use
the fetch API to retrieve some JSON for
your web application okay so essentially
the fetch API is going to do two things
it's going to first make the request to
retrieve the JSON file and then it's
going to take the JSON contents and pass
it as a regular JavaScript object okay
so I've got here in my text editor an
index.html file and also a people dot
JSON file right in the same directory
okay so we have here just a regular JSON
object with a date and some people in an
array okay so we're going to be
retrieving this right here using the
fetch API so back inside the index.html
file let's go inside the JavaScript and
firstly just make a new fetch request
okay so we're gonna write fetch down
here and pass in here people with dot
JSON so the URL of the JSON file okay so
once the request has came back and we
have a response this function inside
here is going to be executed so we have
access to the response through the first
argument alright so the response
contains a few useful methods one of
them being txt and one of them being
JSON so we're going to use the JSON
method on the response object to
actually parse the JSON into a regular
JavaScript object once it has been
retrieved
okay so inside of this function we're
gonna return response dot JSON as I said
this is gonna attempt to convert the the
body of the response which in this case
is going to be JSON it's going to
interpret it as JSON and try to convert
it to a JavaScript object it will then
return a new promise okay so in this new
promise
we ever then and this function inside
here has access to the actual past
JavaScript object okay so we have that
right there as the first argument okay
so now we have the actual object I can
then simply just say console download
and print out the object all right if
anything went wrong during the whole
process we're going to use the catch
method down here and we're going to
simply just print out the error so we
can just say consult or error something
went wrong we're retrieving other people
now this would be a network error or it
could be a JSON parsing error okay so
I'll just console dot error the error
okay
so I can now save this and now refresh
my browser and we should see the object
in the console and we get it right here
okay so it worked
nice and well okay so let's say I was to
accidentally and make a mistake inside
my JSON so if I get rid of that and
cause a an actual error in the JSON
syntax and now refresh the browser this
time we see here we get the error so
something went wrong and we have seen
second right here unexpected token curly
brace in JSON so that is the catch
working all right
and that right there is how you can
retrieve JSON using the fetch API thanks
for watching and I will see you later