6

我有一个 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,
        ...
    }
]

来自的 idclients.json与关联详细信息所在的文件夹相关。

我在客户端文件夹中有很多 JSON 文件,而不是在客户端单独加载这些文件,我想使用 Node.js 创建一个 API,这给了我更大的灵活性,即..

返回客户端名称和 ID 的列表 /clients

返回客户详细信息 /clients/:id/details

最重要的是返回所有客户名称和相关详细信息 /clients/all/details

我确实开始使用json-server,但是它要求你的 JSON 是一个对象而不是一个数组,不幸的是我被这个 JSON 的格式所困扰。

感谢任何帮助!

4

5 回答 5

4

使用内置文件系统模块从文件系统中获取文件。

参考这里

这是一个例子。

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.
}
于 2016-12-31T19:20:12.213 回答
2

您可以require将 json 直接作为节点中的对象,如下所示:

app.get('/clients/:id/details', (req, resp) => {
  const id = req.params.id;
  const data = require(`./clients/${id}/client.json`); // or whatever path
  resp.send(data)
});
于 2016-12-28T21:13:53.113 回答
2

你并没有你想象的那么卡。

您必须将数组包装在一个对象中。然后,在前端,您只需要访问数组属性。

毕竟,JSON 是J ava s cript Object Notation的字母缩写。

编辑:好吧,让我们尝试一些新的东西......

也许在使用来自 json-server 的代码之前,做一些预处理。假设该变量clientJson是您已经阅读的文件,请在使用 json-server 中的任何代码之前插入此代码:

clientJson = "{root:"+clientJson+"}";

这会将文件包装在第一个属性为root.

之后,很容易找回你的数组:

clientData = clientData.root;
于 2016-12-09T00:43:45.677 回答
1

您应该使用从 FS 模块读取流向客户端发送数据,在发送后捕获可能的错误并清理内存。

于 2017-01-03T20:03:23.357 回答
1

如果您将文件夹结构上传到云服务(例如 Amazon S3 或 Dropbox)并从那里提供服务,则无需任何代码即可完成此操作。无需代码。

于 2017-01-02T23:51:12.410 回答