0

I watched a YouTube video trying to learn JSON for the first time. This is the example we did during the video, but at '[ I get an Invalid Token error when looking at the console. Sorry for the noob question! Thanks again.

<html>
<head>
    <title>JSON Example</title>
</head>
<body>
    <script type="text/javascript">
        let companies =
        '[
    {
        "name": "Big Corporation",
        "numberOfEmployees": 10000,
        "ceo":  "Mary",
        "rating": 3.6
    },
    {
        "name": "Small Startup",
        "numberOfEmployees": 3,
        "ceo": null,
        "rating": 4.3
    }
]'
    console.log(JSON.parse(companies))
    ((companies)[0].name)
    </script>
</body>
</html>
ChrisM
  • 1,565
  • 14
  • 24
John1776
  • 58
  • 6

1 Answers1

1

The problem is not a JSON one but a JavaScript one. You have to use a particular syntax for multiline strings in JavaScript.

There are multiple ways of doing this but probably the simplest is to use backticks.

<html>
<head>
    <title>JSON Example</title>
</head>
<body>
    <script type="text/javascript">
        let companies =
        `[
    {
        "name": "Big Corporation",
        "numberOfEmployees": 10000,
        "ceo":  "Mary",
        "rating": 3.6
    },
    {
        "name": "Small Startup",
        "numberOfEmployees": 3,
        "ceo": null,
        "rating": 4.3
    }
]`
    console.log(JSON.parse(companies))
    ((companies)[0].name)
    </script>
</body>
</html>

PS: As an aside you'll also get an error on the last line ((companies)[0].name) because the output of console.log isn't a function. Presumably you want another call to console.log

ChrisM
  • 1,565
  • 14
  • 24