Home > database >  Expected a JSON object, array, or literal
Expected a JSON object, array, or literal

Time:12-05

I've copied code from a course I'm taking and it's throwing an error. The message reads "Expected a JSON object, array, or literal" and I'm not entirely sure what I've done wrong since I'm new to using API's (fetch). Here is the screenshot from VSCode. https://www.screencast.com/t/D5oreexoCKq.

In addition to that, this is the error that I'm getting in Chrome. https://www.screencast.com/t/Je4crxQQ4sz6

file -----> data.json

const json = {
    "books": [
        {
            "title": "Learn to Code",
            "author": "John Smith",
            "isbn": "324-23243"
        }, {
            "title": "The Adventures JSON",
            "author": "Jason Jones",
            "isbn": "3324-2-444"
        }, {
            "title": "New Objects",
            "author": "Jane Doe",
            "isbn": "2343-234-2433"
        }
    ]
}

file -----> app.js

JSON.books.forEach(function(val){
  console.log(val);
})

CodePudding user response:

In a json file , there is no need to declare a data with const keyword.

your data.json should be like this

{
  "books": [{
    "title": "Learn to Code",
    "author": "John Smith",
    "isbn": "324-23243"
  }, {
    "title": "The Adventures JSON",
    "author": "Jason Jones",
    "isbn": "3324-2-444"
  }, {
    "title": "New Objects",
    "author": "Jane Doe",
    "isbn": "2343-234-2433"
  }]
}

CodePudding user response:

Your script in app.js needs to actually fetch the JSON file. Using the JSON object in the way you have done will not work. JSON.books is undefined.

Do something like

fetch("books.json").then(r=>r.json()).then(({books})=>{
  books.forEach(book=>console.log(book))
})

in your app.js file. This is assuming that book.json can be found in the same folder as app.js and index.html.

  • Related