JavaScript Fetching External Data

JSON

We now have a firm grip on how to interact with APIs, but have yet to decide the shape of the data that we send and receive.

There are essentially two shapes that we can choose between:

  • XML: Extensible Markup Language is a markup language that is used to store and trasnport data.
  • JSON: JavaScript Object Notation is a data-interchange format that supports many of JavaScript's own built-in types. JavaScript provides the JSON.parse method to convert text to JSON and the JSON.stringify to convert JSON to text.

Most RESTful APIs we'll meet, as well as most non-RESTful APIs, respond with JSON by default, or at least has an option to return JSON.

Read more on MDN

JSON

Code example: object to text and back

const person = {
firstName: "Ola",
lastName: "Nordmann",
}
console.log(person.firstName) // "Ola"
const asText = JSON.stringify(person)
console.log(asText) // '{"firstName":"Ola","lastName":"Nordmann"}'
const asJSObj = JSON.parse(asText)
console.log(asJSObj.firstName) // "Ola"
console.log(asText.firstName) // undefined
// string is not an object