我有一个 JSON 文件文件夹,我想用它来创建一个简单的 API。
这是我的文件夹结构的简化版本:
/clients.json
/clients/1/client.json
/clients/2/client.json
...
我的 /clients.json
文件如下所示:
[
{
"id": 1,
"name": "Jon Parker"
},
{
"id": 2,
"name": "Gareth Edwards"
},
...
]
我的 /clients/1/client.json
文件如下所示:
[
{
"date": "2014-09-12",
"score": 40,
...
},
{
"date": "2015-02-27",
"score": 75,
...
},
{
"date": "2015-05-10",
"score": 75,
...
},
{
"date": "2016-08-27",
"score": 60,
...
}
]
clients.json
中的 id 与相关详细信息所在的文件夹相关。
我在客户端文件夹中有很多 JSON 文件,而不是在客户端单独加载这些文件,我想使用 Node.js 创建一个 API,它给我更多的灵 active ,即......
返回客户名称和 ID 的列表
/客户
返回客户详细信息
/clients/:id/details
最重要的是返回所有客户的姓名和相关详细信息
/clients/all/details
我确实开始玩 json-server ,但是它要求您的 JSON 是一个对象而不是一个数组,不幸的是我坚持使用这种 JSON 的格式。
感谢任何帮助!
最佳答案
使用内置的文件系统模块从文件系统中获取文件。
这是一个例子。
var fs = require('fs');
exports.getClientDetail = function (id) {
var result;
fs.readFile('/clients/' + id + '/client.json', function (err, data) {
if (err) throw err;
result.push(JSON.parse(data));
});
}
exports.getAllClientsDetail = function () {
// if the id is sequential, you can check if '/clients/' + id + '/client.json' exists for every i from 1 and up. If it does - push it to an array of objects. if for a certain i it does not exist, quit the scan and return the array of objects.
}
关于javascript - 从 JSON 文件创建简单的 Node.js API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41051295/