【问题标题】:How can I get data in json array by ID?如何通过 ID 获取 json 数组中的数据?
【发布时间】:2021-05-04 20:26:05
【问题描述】:

当我转到 URL /user/:id 时,我想检索有关该 ID 的所有信息作为响应。

这是data.json

{
  "id": 1,
  "name": "name1"
    
},
{
  "id": 2,
  "name": "name2"
}
    

这是index.js

var express = require('express');
var app = express();

app.get('/user/:id', function(req, res) {
    // do stuff here
})

app.listen(3000)

【问题讨论】:

    标签: node.js arrays json express


    【解决方案1】:

    首先,你的 JSON 必须是一个数组,所以把它改成

    [
        {
            "id": 1,
            "name" : "name1"
            
        },
        {
            "id" : 2,
            "name" : "name2"
        }
    ]
    

    然后在你的快递csode上

    var express = require('express');
    var fs = require('fs'); // util to read file
    var app = express();
    
    /**
    JSON.parse is a function to parse string with JSON format to JavaScript object
    fs.readFileSync is a function to read file synchronously, first parameter is the path to the file, 
    second parameter is the encoding type
    */
    var users = JSON.parse(fs.readFileSync('path/to/data.json', 'UTF-8'));
    // users now is [{ id: 1, name : "name1" }, { id : 2, name : "name2" }]
    // users[0].name will gives you name1
    
    app.get('/user/:id', function(req, res) {
        var id = +req.params.id; // will contains data from :id, the + is to parse string to integer
        var user = users.find(u => u.id === id); // find user from users using .find method
        res.send(user); // send the data
    })
    
    app.listen(3000);
    

    【讨论】:

      猜你喜欢
      • 2011-12-31
      • 2013-01-22
      • 1970-01-01
      • 1970-01-01
      • 2019-03-19
      • 2020-10-26
      • 2017-01-07
      • 1970-01-01
      • 2021-02-15
      相关资源
      最近更新 更多