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

时间:2018-03-08 13:45:46

标签: javascript json

我正在尝试创建一个 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": ""
        }
    ]
}

正如您所见,预测数组包含2个名为早晨下午的JSON对象。

但是通过这种方式,我获得了以下错误消息,试图在验证器(https://jsonlint.com/)上验证此JSON文档,获得的错误是:

  

错误:第3行解析错误:...施放“:[”上午“:{”日期“:   “01/1   ---------------------- ^期待'EOF','}',',',']',得到':'

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

var popup = window.open("http://google.com", "_blank", "width=600,height=600");

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

2 个答案:

答案 0 :(得分:2)

你错过了数组元素周围的大括号:

{
    "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
    ]
}

答案 1 :(得分:1)

你拥有的是无效的JSON。数组元素不能有“名称”,因为这只是一个对象......

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

另一种方法是将名称放在数组中的对象内。

mvn clean test -Dsurefire.suiteXmlFiles=WebCheckout.xml