Home > other >  Error with JSON data ("Expected a JSON object, array or literal")
Error with JSON data ("Expected a JSON object, array or literal")

Time:10-18

I'm following a JSON tutorial and I've run into a problem.

I'm using Visual Studio Code, and I have an HTML file, a JS file, and a JSON file. Even though the data in the JSON file is (to the best of my understanding) correctly formatted, VSCode gives me the following error:

Expected a JSON object, array, or literal.

Right now, the JS file is empty. The code in my HTML file is as follows:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h1>SANDBOX</h1>
    <div >

    </div>
</body>
<script src="data.json"></script>
<script src="app.js"></script>

</html>

and the data in my .JSON file is:

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"
    }]
};

I don't understand why I'm getting this error.

Things I've tried:

  1. Following the tutorial - The tutor doesn't seem to have this problem, for some reason.

  2. Wrapping the JSON data in curly braces - This just throws three more errors: Property keys must be doublequoted, Colon expected, and End of file expected.

  3. Searching this site for similar questions - I've found similar questions, but the solutions offered don't solve my problem. I'm always left with the original error, 'Expected a JSON object, array or literal'.

Any help you could provide would be very much appreciated.

CodePudding user response:

you can't use javascript inside .json file

change .json file to

[{
        "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"
    }]

instead load your json file inside the app.js

const books = require("my.json")

BUT

if you wish to use it like that then you have to change the format of my.json to my.js

  • Related