javascript - 为什么我无法验证这个包含包含命名对象的数组的 JSON 文档?

标签 javascript json

我正在尝试创建一个包含对象数组的 JSON 文档,其中每个对象都有一个特定的“名称”,因此我创建了这个 JSON 文档:

{
    "forecast": [
        "morning": {
            "date": "01/10/2018",
            "min_temp": "12",
            "max_temp": "24",
            "humidity": "2",
            "wind_direction": "SO",
            "wind_force": "12",
            "status": "OK",
            "description": "sdfsdfsdf"
        },
        "afternoon": {
            "date": "01/10/2018",
            "min_temp": "",
            "max_temp": "",
            "humidity": "",
            "wind_direction": "",
            "wind_force": "",
            "status": "",
            "description": ""
        }
    ]
}

如您所见,forecast 数组包含 2 个名为 morningafternoon 的 JSON 对象。

但是这样我在尝试在验证器( https://jsonlint.com/ )上验证这个 JSON 文档时得到以下错误消息,得到的错误是:

Error: Parse error on line 3: ...cast": [ "morning": { "date": "01/1 ----------------------^ Expecting 'EOF', '}', ',', ']', got ':'

以这种格式更改以前的 JSON 文档(基本上删除 JSON 对象名称),它工作正常并且经过正确验证:

{
    "forecast": [
        {
            "date": "01/10/2018",
            "min_temp": "12",
            "max_temp": "24",
            "humidity": "2",
            "wind_direction": "SO",
            "wind_force": "12",
            "status": "OK",
            "description": "sdfsdfsdf"
        },
        {
            "date": "01/10/2018",
            "min_temp": "",
            "max_temp": "",
            "humidity": "",
            "wind_direction": "",
            "wind_force": "",
            "status": "",
            "description": ""
        }
    ]
}

为什么第一个版本没有经过验证?我可以将对象名称放入 JSON 文档的数组中吗?或者我是否需要添加上午下午信息作为每个对象的值字段?

最佳答案

您缺少数组元素周围的大括号:

{
    "forecast": [
      {  // HERE
        "morning": {
            "date": "01/10/2018",
            "min_temp": "12",
            "max_temp": "24",
            "humidity": "2",
            "wind_direction": "SO",
            "wind_force": "12",
            "status": "OK",
            "description": "sdfsdfsdf"
        },
        "afternoon": {
            "date": "01/10/2018",
            "min_temp": "",
            "max_temp": "",
            "humidity": "",
            "wind_direction": "",
            "wind_force": "",
            "status": "",
            "description": ""
        }
      }  // HERE
    ]
}

关于javascript - 为什么我无法验证这个包含包含命名对象的数组的 JSON 文档?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49174643/

相关文章:

javascript - 如何从此 API 链接获取数据?

javascript - 如何使用 Airbnb JavaScript 样式指南设置 Prettier

javascript - Microsoft JScript 运行时错误 : 'DeleteRowFromCart' is undefined

json - PostgreSQL 中 JSON 数据类型的大小限制

java - 在 TextView 中显示 json 值

java - 如何将日志发送到 JSON Web 服务?

java - http 的正确 JSON 格式、正确的 JSON 转义宪章

JavaScript 循环结束 NaN 用于数字加法

javascript - 使用 Array.includes 使用一个键检查数组是否包含对象

javascript - 语法错误 :invalid o unexpeted toked