应为JSON对象,数组或literal.json

时间:2018-12-17 22:10:02

标签: javascript arrays json error-handling literals

我有一个JSON文件,用于存储正在构建的Quote Generator的报价。 最近,我在终端中收到此错误(请参见下面的屏幕截图)。

Expected a JSON object, array or literal.json

这是我的JSON的样子

data = [
{
    "number": "1",
    "author": "Von R. Glitschka",
    "quote": "The client may be king, but he's not the art director."
},
{
    "number": "2",
    "author": "Frank Capra",
    "quote": "A hunch is creativity trying to tell you something."
},
{
    "number": "3",
    "author": "Steven Heller",
    "quote": "As a profession, graphic designers have been shamefully remiss or ineffective about plying their craft for social or political betterment."
}]

我已经尽力了。但是错误不断出现,这可能是什么问题?

enter image description here

4 个答案:

答案 0 :(得分:0)

您只需要像这样格式化文件即可:

{
  "data" : [
    {
        "number": "1",
        "author": "Von R. Glitschka",
        "quote": "The client may be king, but he's not the art director."
    },
    {
        "number": "2",
        "author": "Frank Capra",
        "quote": "A hunch is creativity trying to tell you something."
    },
    {
        "number": "3",
        "author": "Steven Heller",
        "quote": "As a profession, graphic designers have been shamefully remiss or ineffective about plying their craft for social or political betterment."
    }]
}

并使用扩展名.json保存。

答案 1 :(得分:-1)

在给定您拥有的数据和用于获取随机数的代码的情况下,您的数字通常超出数组中对象的数量。

例如

Math.floor(Math.random() * 50)

最终可能将random设置为13,这大大超出了数组中的值数量。

如果您想获得0到2之间的随机数,可以使用:

random = Math.floor(Math.random() * Math.floor(3));

答案 2 :(得分:-1)

一种替代方法是

data = [
{
"number": "1",
"author": "Von R. Glitschka",
"quote": "The client may be king, but he's not the art director."
},
{
"number": "2",
"author": "Frank Capra",
"quote": "A hunch is creativity trying to tell you something."
},
{
"number": "3",
"author": "Steven Heller",
"quote": "As a profession, graphic designers have been shamefully remiss or ineffective about plying their craft for social or political betterment."
}];

console.log(data);
var random = Math.floor(Math.random() * data.length); 
console.log(data[random].quote);
console.log(data[random].author);

答案 3 :(得分:-2)

首先,这不是JSON格式。这是一个对象数组。 您的JSON不能像您那样拥有变量分配      var data = .....  取决于获取错误的原因或打算如何处理数据。您有2个选择:

  1. 将此数组转换为可接受的JSON对象,如下所示: $ JSON.stringify(data)

  2. 您可以将这些数据直接作为数组使用,只需将其存储为js变量或js文件即可。然后,您可以像数组一样轻松地对其进行操作。