0

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 class="output">

    </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.

1
  • Your file name is .json but the content is javascript. Try renaming it to .js or removing const json = (but not both). Commented Oct 16, 2021 at 19:30

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.