JSON - 无效的令牌

我第一次观看了尝试学习 JSON 的 YouTube 视频。这是我们在视频中所做的示例,但是在 '[ 我在查看控制台时收到无效令牌错误。对不起,菜鸟问题!再次感谢。


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


慕标琳琳
浏览 237回答 1
1回答

30秒到达战场

问题不是 JSON,而是 JavaScript。您必须对 JavaScript 中的多行字符串使用特定的语法。有多种方法可以做到这一点,但最简单的可能是使用反引号。<html><head>&nbsp; &nbsp; <title>JSON Example</title></head><body>&nbsp; &nbsp; <script type="text/javascript">&nbsp; &nbsp; &nbsp; &nbsp; let companies =&nbsp; &nbsp; &nbsp; &nbsp; `[&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; "name": "Big Corporation",&nbsp; &nbsp; &nbsp; &nbsp; "numberOfEmployees": 10000,&nbsp; &nbsp; &nbsp; &nbsp; "ceo":&nbsp; "Mary",&nbsp; &nbsp; &nbsp; &nbsp; "rating": 3.6&nbsp; &nbsp; },&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; "name": "Small Startup",&nbsp; &nbsp; &nbsp; &nbsp; "numberOfEmployees": 3,&nbsp; &nbsp; &nbsp; &nbsp; "ceo": null,&nbsp; &nbsp; &nbsp; &nbsp; "rating": 4.3&nbsp; &nbsp; }]`&nbsp; &nbsp; console.log(JSON.parse(companies))&nbsp; &nbsp; ((companies)[0].name)&nbsp; &nbsp; </script></body></html>PS:顺便说一句,你还会在最后一行得到一个错误,((companies)[0].name)因为 的输出console.log不是一个函数。大概你想要另一个电话console.log
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript