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

问题描述 投票:0回答:5

我有一个 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."
}]

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

enter image description here

javascript arrays json error-handling literals
5个回答
11
投票

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

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


0
投票

我有一个类似的问题,但最终是这样想出来的: 首先,你需要确保你有一个 eslintrc.json 文件,然后在那个 json 文件中添加这个 json 对象:

{ “延伸”:[ “插件:反应/推荐”, “插件:@typescript-eslint/推荐”, “插件:更漂亮/推荐” ] }

如果您有打字稿或更漂亮的错误,这也有效。


-3
投票

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

例如,

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

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

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

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

-3
投票

另一种方法是

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

-4
投票

首先,这不完全是一种 JSON 格式。这是一个对象数组。 您的 JSON 不能像您拥有的那样具有变量赋值

var data = .....
取决于您收到错误的原因或您打算如何处理数据。您有 2 个选择:

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

    $ JSON.stringify(data)
    .

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

© www.soinside.com 2019 - 2024. All rights reserved.