简体   繁体   English

Json-server 错误:数据必须是对象。 需要将 JSON 数组更改为 JSON 对象

[英]Json-server Error: Data must be an object. Need to change JSON Array to JSON Object

I can't start my json-server, because this REST API : gives me a JSON Array, but I need a JSON Object to run json-server.我无法启动我的 json-server,因为这个REST API :给了我一个 JSON 数组,但我需要一个 JSON 对象来运行 json-server。 Is it possible to run json-server with an JSON Array, or can I construct my own db.json?是否可以使用 JSON 数组运行 json-server,或者我可以构建自己的 db.json?

I've tried to put the JSON Array into a db.json file and removing the squared brackets, but because it was an array previous, the commas give me an error.我试图将 JSON 数组放入 db.json 文件并删除方括号,但因为它是以前的数组,逗号给了我一个错误。 So manually changing db.json is also not possible.所以手动更改 db.json 也是不可能的。

npm json-server --port 3001 --watch db.json

fires this error message:触发此错误消息:

Error: Data must be an object.错误:数据必须是对象。 Found object.See https://github.com/typicode/json-server for example.找到对象。例如,参见https://github.com/typicode/json-server

UPDATE: I've simply wrapped the array with curly braces and added a property to it like this:更新:我只是用花括号将数组包裹起来,并为它添加了一个属性,如下所示:

{ "countries": [{"name": ...

...

}]}

Now I've got a JSON Object in db.json and I can run json-server.现在我在 db.json 中有一个 JSON 对象,我可以运行 json-server。

In case others get here.以防其他人来到这里。 Assuming you have an array of countries with their names, you want it in the form假设您有一组带有名称的国家/地区,您希望它的形式为

{ 
    "countries": [ {"id": 1, "name": "Narnia"}, {"id":2, "Sacoridia"}, ...]
}

The server can simulate multiple "tables" so you could add another line like服务器可以模拟多个“表”,因此您可以添加另一行,例如

    "cities": [ {"id":1, "country_id": 1, "name":"Cair Paravel", "capital":1},...]

Since the data is in the form [{"name":"country name", ...}, {"name":"country name 2", ...}, ... ] , you'd have to transform it by extracting for example the name, or whatever attribute you want, as key, to get the format { "country name": { ... }, "country name 2": { ... },... } .由于数据的形式为[{"name":"country name", ...}, {"name":"country name 2", ...}, ... ] ,您必须转换它通过提取例如名称或您想要的任何属性作为键来获取格式{ "country name": { ... }, "country name 2": { ... },... }

For example, this could be done with Javascript as:例如,这可以用 Javascript 来完成:

function transform(data) {
  var transformedObject = {};
  for(var i = 0; i < data.length; i++) {
    transformedObject[data[i].name] = data[i];
  }
  return transformedObject;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM