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 badges2 Answers
Reset to default 5In 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;
}