通过本地json http通过ID获取

时间:2018-07-05 11:04:56

标签: json node.js http

我有伪造的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数据。

感谢您的帮助。 谢谢

3 个答案:

答案 0 :(得分:1)

如果您需要json作为原始数据,那么对于假数据,您只需将其用作对象即可。

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

此外,如果您需要更多动态解决方案,可以使用一个不错的JSON服务器轻松进行测试,因此:check this git repo

答案 1 :(得分:1)

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;
})

答案 2 :(得分:0)

  1. 使用JSON.parse('users.json')获取JSON对象并将其存储在可变用户中。
  2. 使用for .. in并在if上使用id条件遍历用户数组,如果需要,则更新对象。
  3. 使用JSON.stringify更新的用户对象。并使用NodeJS中的fs.write()模块将此字符串写入users.json文件,以便在json文件中拥有更新的对象。