DEV Community

Jeremy Oliver
Jeremy Oliver

Posted on • Updated on

JSON and the .then

During the course of learning JavaScript I came upon a universal data type I didn't quite understand. I educated myself and thought it might benefit another newbie to make a write up of what JSON is, and how it works.

JSON

JSON stands for Java Script Object Notaion and is the standard for sending data from a web page to a server, and vice versa. The reason for it to exist is to to transport data in a standardized way across the web.

An example of JSON is below. The text of JSON is always in key-value pairs, which represents an "object like" format with some key differences. Because the syntax of JSON is identical to that of a JavaScript object, it can easily be read and converted by JavaScript.

{
 "employees":[
    {"firstName":"John", "lastName":"Doe"},
    {"firstName":"Anna", "lastName":"Smith"},
    {"firstName":"Peter", "lastName":"Jones"}
 ]
}
Enter fullscreen mode Exit fullscreen mode

The key difference, however, is that JSON is text only. This means any programming language can read and write from it, even though it follows the syntax of JavaScript objects.

The syntax rules from the JSON documentation are as follows:

Data is in name/value pairs
Data is separated by commas
Curly braces hold objects
Square brackets hold arrays
Enter fullscreen mode Exit fullscreen mode

Sending and Receiving JSON

Because JSON is considered text only and not a collection of actual JavaScript objects, we can't treat them the same way as JavaScript objects. This is why when you FETCH data, and that data is returned in JSON format, we must grab the JSON and convert it into a JavaScript object using the a built in method, like so:

fetch('https://api.books.com') // Fetches a JSON document 
 of books from our fake API
.then(res => response.json()) // Turns JSON into 
 JavaScript object literal
.then(data => console.log(books)); // Logs books to 
 console
Enter fullscreen mode Exit fullscreen mode

After we grab and convert the JSON plain text file into a JavaScript object, or collection of objects, we are free to use the data as JS objects within our code.

Using the JSON Objects

We use the objects we interpreted from our JSON file by using another .then statement. For example, if we were importing a list of books, we would use:

.then(response => response.json())
Enter fullscreen mode Exit fullscreen mode

followed by:

.then(function(books) {
*Your code to interact with the books objects goes here*
} // This code snippet uses the book objects in a function 
  instead of printing them to the console like in our last 
  example
Enter fullscreen mode Exit fullscreen mode

By using response => response.json() followed by using a second .then with a function you can interact with those objects that were interpreted from your JSON document. As I mentioned earlier, JSON documents do not contain objects. Our first .this interpreted the JSON into a readable format to be used by JavaScript as objects. We can now interact with every "book" in our JSON document by using the book object we passed in to our function!

We can interact with these objects and can manipulate them the same way as any other object we have created. We can use key/value pairs, update them, and in turn, update the database with with the changes by submitting an updated version of the JSON file.

Sending Objects to an API With JSON.stringify()

Now that we have fetched our books from the API, how would be add a book and send it back to update the API?

To start, we would need to create a new book object to send that might look like this:

const newBook = {
  category: ['fantasy']
  book: 'Harry Potter and the Sorcerers Stone'
}
Enter fullscreen mode Exit fullscreen mode

After the book object is created we need to "stringify" the object. This turns our object into a string and thus is in JSON format, ready to be uploaded to our fake books API.

JSON.stringify(newBook);
Enter fullscreen mode Exit fullscreen mode

We can add this book to our fake books API with a POST request as follows

fetch('https://api.books.com/submit', { // fake books API 
 endpoint
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(newBook), // Turns the iteral object 
 into a string of JSON
})
Enter fullscreen mode Exit fullscreen mode

We have created a new book object, and POSTed it to our books API using JSON.stringify() to turn our JavaScript Object literal into a JSON string!

Summary

the JSON is formatted as a string, which only looks like an object. This is so that it can be used by many different technologies and always behave the same. We have built in functions within JavaScript to FETCH JSON data, and to turn it into JS literal objects. We have other built in functions within JavaScript to turn objects into JSON and POST them to update our JSON document.

Thank you for reading and please let me know if you enjoyed my first blog post!

Top comments (0)