【问题标题】:Create Simple Node.js API from JSON files从 JSON 文件创建简单的 Node.js API
【发布时间】:2017-04-24 09:26:52
【问题描述】:

我有一个 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,让我更加灵活,即...

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

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

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

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

感谢任何帮助!

【问题讨论】:

  • 加载数据后可以将数组转换为对象;执行 JIT 不会花费太长时间,并且会为您提供 API 所期望的键控。

标签: javascript json node.js json-server


【解决方案1】:

你并没有你想象的那么困难。

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

毕竟,JSON 是 Javascript Object Notation 的首字母缩写。

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

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

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

这会将文件包装在第一个属性为root 的对象中。

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

clientData = clientData.root;

【讨论】:

  • 这是真的,但是这些 JSON 文件是自动生成的,我无法控制,手动编辑它们并不是一个真正的选择
  • 为什么没有手动编辑选项?这些动态文件,即不断变化?
【解决方案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)
});

【讨论】:

  • 请注意,如果 require 无法解析文件,它将抛出异常。它还将缓存所需的文件。
  • Q 或 A 中是否缺少标签,或者节点是否有新的.get 方法?
  • 假设是 express ,我注意到 DanV 提到了 express 使用的/clients/:id/details 路径语法。
【解决方案3】:

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

Refer here

这是一个例子。

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.
}

【讨论】:

    【解决方案4】:

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

    【讨论】:

      【解决方案5】:

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

      【讨论】:

        猜你喜欢
        • 2015-06-24
        • 1970-01-01
        • 2021-02-02
        • 1970-01-01
        • 2016-11-07
        • 2017-11-08
        • 2021-11-02
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多