最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Json-server Error: Data must be an object. Need to change JSON Array to JSON Object - Stack Overflow

programmeradmin0浏览0评论

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. Is it possible to run json-server with an JSON Array, or can I construct my own 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 mas give me an error. So manually changing db.json is also not possible.

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

fires this error message:

Error: Data must be an object. Found object.See for example.

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.

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. Is it possible to run json-server with an JSON Array, or can I construct my own 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 mas give me an error. So manually changing db.json is also not possible.

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

fires this error message:

Error: Data must be an object. Found object.See https://github./typicode/json-server for example.

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.

Share Improve this question edited Aug 28, 2019 at 13:30 Fatih Kahraman asked Aug 28, 2019 at 12:15 Fatih KahramanFatih Kahraman 311 gold badge1 silver badge5 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

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": { ... },... }.

For example, this could be done with Javascript as:

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

评论列表(0)

  1. 暂无评论