javascript 应为JSON对象、数组或literal.json

cgh8pdjw  于 2023-03-28  发布在  Java
关注(0)|答案(5)|浏览(283)

我有一个JSON文件,我用它来存储我正在构建的一些报价生成器的报价。最近,我在我的终端中得到了这个错误(见下面的截图)。
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."
}]

我已经尽力了,但是错误还是不断出现,到底是什么问题呢?

taor4pac

taor4pac1#

你只需要像这样格式化你的文件:

{
  "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扩展名保存此文件。

qvtsj1bj

qvtsj1bj2#

我也遇到过类似的问题,但最后还是这样解决了:首先,你需要确保你有一个eslintrc.json文件,然后在这个json文件中添加这个json对象:
{“延伸”:[“plugin:react/recommended”,“plugin:@typescript-eslint/recommended”,“plugin:prettier/recommended”] }
如果你有一个 typescript 或漂亮的错误,它也可以工作。

v2g6jxz6

v2g6jxz63#

看起来,给定您拥有的数据和用于获取随机数的代码,您的数字通常超过数组中的对象数量。
比如说

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

最终可能会将random设置为13,这大大超过了数组中的值的数量。
如果你想得到一个0到2之间的随机数,你可以用途:

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

yshpjwxd4#

对此的替代方法是

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);
x8goxv8g

x8goxv8g5#

首先,这并不是一个JSON格式。这是一个对象数组。你的JSON不能像var data = .....那样有一个变量赋值,这取决于你为什么会得到错误或者你打算对数据做什么。你有两个选择:
1.将此数组转换为可接受的JSON对象,如下所示:$ JSON.stringify(data) .
1.你可以直接将这些数据作为数组来处理,只需要将其存储为js变量或js文件,然后你就可以像处理数组一样轻松地处理它。

相关问题