【问题标题】:get by id from local json http从本地 json http 通过 id 获取
【发布时间】:2018-12-13 20:12:34
【问题描述】:

我有伪造的users.json 文件,我可以http.get 列出json 数组。 由于我想通过 id 获取特定用户并且没有将数据存储在数据库中,因此只需使用伪造的 json 数据。

[
  {
    "id": "cb55524d-1454-4b12-92a8-0437e8e6ede7",
    "name": "john",
    "age": "25",
    "country": "germany"
  },
  {
    "id": "ab55524d-1454-4b12-92a8-0437e8e6ede8",
    "name": "tom",
    "age": "28",
    "country": "canada"
  }
]

如果数据存储在数据库中,我可以做这些事情,但不确定如何处理假的 json 数据。

感谢任何帮助。 谢谢

【问题讨论】:

    标签: json node.js http


    【解决方案1】:
    1. 使用 JSON.parse('users.json') 获取 JSON 对象并将其存储在变量 users 中。
    2. 使用for .. in 循环遍历用户数组,并在id 上使用if 条件,根据需要更新对象。
    3. 使用 JSON.stringify(users) 对更新的用户对象进行字符串化;并使用 NodeJS 中的 fs.write() 模块将此字符串写入 users.json 文件,这样您的 json 文件中就会有更新的对象。

    【讨论】:

      【解决方案2】:

      如果您需要 json 作为原始数据,对于假数据,您可以简单地要求它并将其用作对象..

      const JsonObj = require('path/to/file.json')
      console.log(JsonObj[0].id) // <-- cb55524d-1454-4b12-92a8-0437e8e6ede7
      

      另外,如果您需要更动态的解决方案,有一个很好的 JSON 服务器可以轻松用于测试,因此:check this git repo

      【讨论】:

        【解决方案3】:
        var _ = require('underscore');
        
        var dummyJson = [
          {
            "id": "cb55524d-1454-4b12-92a8-0437e8e6ede7",
            "name": "john",
            "age": "25",
            "country": "germany"
          },
          {
            "id": "ab55524d-1454-4b12-92a8-0437e8e6ede8",
            "name": "tom",
            "age": "28",
            "country": "canada"
          }
        ]
        
        var requiredID = "cb55524d-1454-4b12-92a8-0437e8e6ede7";
        
        var reuiredObject = _.find(dummyJson, function (d) {
            return d.id === requiredID;
        })
        

        【讨论】:

          猜你喜欢
          • 2016-02-23
          • 1970-01-01
          • 2018-03-08
          • 2016-02-04
          • 1970-01-01
          • 2013-04-06
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多