loading...
Cover image for Dealing with ".json() is not a function" Error

Dealing with ".json() is not a function" Error

mohammedasker profile image Mohammed Asker ・2 min read

You finished a tutorial about REST API, Ajax, or Fetch and now you're ready to build a new project using API. Cool! You opened a new file in text editor and start typing away until you encounter a problem. When you write .json(), you will get the ".json() is not a function" error.

You could get around by changing it to .text(), however doing this will make it hard to retrieve data you want from API even though it's technically responding. What should you do?

The solution? Use items.

Let me give you a quick example where I used it in my book finder project.

I created a function where it will fetch a data from Google Books API and display the search results in HTML. I simplified the codes just to demonstrated the point.

function searchBook() {
  const query = document.querySelector('#search-input').value;
  fetch(`https://www.googleapis.com/books/v1/volumes?q=${query}`)
      .then((res) => res.json())
      .then((data) => {
        let output = '<h2>Search results</h2>';
        data.forEach(book => {
        // Display search results
      })
  }
Enter fullscreen mode Exit fullscreen mode

This code will not work because there is something missing and prevents the data parameters from being accessed . However, if I add items between data and forEach(), it will work:

function searchBook() {
  const query = document.querySelector('#search-input').value;
  fetch(`https://www.googleapis.com/books/v1/volumes?q=${query}`)
      .then((res) => res.json())
      .then((data) => {
        let output = '<h2>Search results</h2>';
        data.items.forEach(book => {
        // Display search results
      })
  }
Enter fullscreen mode Exit fullscreen mode

Why this happens? To be honest, I still don't fully understand why it works this way either, so I'd be happy if any of you provide a better explanation in the comments below. For the time being, here's my thoughts:

Firstly, It could be the API itself - Not all APIs will work immediately if you simply put .json() and hoped for the best. Some APIs like JSONPlaceholder will work just fine without including items, while others like Google Books API will require to include it to make it work.

Secondly, the API data will be returned in JSON format and since the objects are wrapped inside the array, you will need to get into the array first before you can access the JSON data from which you can then change it into object using the .json().

So there you go! Next time when that error appears again, you know what you're gonna do.

Discussion

pic
Editor guide
Collapse
simonlegg profile image
Simon

Hey, so to add a bit of clarity as to what’s happening here, when you request the data from that URL the JSON response is structured like a Javascript object (JSON stands for JavaScript Object Notation).

When you use the variable data the format of it from that google books API looks something like this:

{
    "child": "books # volumes",
    "totalItems": 3052,
    "items": [
        {
            "child": "books # volume",
            "id": "-lsujEgnWvsC",
            "floor": "OJYGmROmBGg",
            "selfLink": " https://www.googleapis.com/books/v1/volumes/-lsujEgnWvsC ",
            "volumeInfo": {…},
            "saleInfo": {…},
            "accessInfo": {…},
            "searchInfo": {…},
        },
    ],
}

So where you’re wanting to iterate through the list of books, they’re actually available as the items property in the data object.

Just so that you’re aware, adding .items here only really works because of the way that this API returns data. Does that make sense?

Collapse
mohammedasker profile image
Mohammed Asker Author

Yes, yes, and YES!! That actually makes a lot of sense now. I didn't pay attention to that "items" part other than the one where I want to iterate it.

To make a confession, I still don't understand about array and objects because I have no idea when to use them in a real situation. Usually, I internalized the concepts better when I applied it to my projects.

You, my friend, just helped me to "clicked" the object concept.

Collapse
simonlegg profile image
Simon

Awesome! I‘m glad it helped.

Yeah, I remember when I was starting out, Arrays and Objects (or Hashes as they’re known in Ruby which is what I started with!), were so complicated to me, but you’ll get there!

You’ll probably eventually have the day where you’ll go “Ohhhh! This is exactly what I need an Object for!!”

Essentially they’re both kind of lists of things, an Array is kind of “just a list” and an Object is a list of things but you give the things names instead. That’s how I thought about it at least.

Anyways, good luck on the journey!!!

Thread Thread
mohammedasker profile image
Mohammed Asker Author

Yup, I'll eventually reach the "aha" moment. And when I do, then I'll completely build my foundations in JavaScript.

Collapse
dillionmegida profile image
Dillion Megida

I was going to give a comment similar to Simon's till I saw his.

To add,

Objects can be simply referred to as key:value pairs for variables. They have no order exactly, so accessing the variable values, you'd need the keys.

In the json data in Simon's code, key:value would be

"child": "books # volumes"

where "child" is the key. This is the same method applied for the items such that key "items"'s value is an array which contains many objects.

The concept of array is that it contains ordered values such that the keys are the indexes (starting from 0). You access object values with variable.key while array values are with variable[index].

The forEach method applies your specified function to every value in the array. That's the reason you are able to display all search results.

I hope this helps too.

Thread Thread
mohammedasker profile image
Mohammed Asker Author

I love this explanation too!

If I understand it correctly, the object is nothing more than just storing unordered pairs. Key are usually strings, while values can be literally anything. And to use them, I'll have to add key next to a variable which in my post example happens to be items

Basically, object stores key:value and array store object.

If this is how the object works, then I can say with confidence that I know what object is and when to use them. (At least when working on an API)

Thread Thread
dillionmegida profile image
Dillion Megida

Yes, you're right : )