Home > database >  How to retrieve the particular data set from JSON file in Node.js?
How to retrieve the particular data set from JSON file in Node.js?

Time:10-10

Below you can see my user.json file

     [
       {
          "id":1,
          "name":"Jhone",
          "username":"Jhone123",
       },
       {
          "id":2,
          "name":"Ervin",
          "username":"Ervin123",
       },
       {
          "id":3,
          "name":"Bauch",
          "username":"Bauch123",
       },
       {
          "id":4,
          "name":"Lebsack",
          "username":"Lebsack123",
       },
       {
          "id":5,
          "name":"Kamren",
          "username":"Kamren123",
       }
    ]

Here is my Node.js Server

const express = require('express')
const app = express()
const port = 8080
var users = require('./users');

app.get('/user/:uid', (req, res) => {s
  let jsonString = JSON.stringify(users[0]);
  res.send(jsonString);
});

app.listen(port, () => {
    console.log(`app listening at http://localhost:${port}`)
  });

How do I send the data according to the uid?

Ex: http://localhost:8080/user/uid=1

When I use uid=1, Output should be like below

 {
     "id":1,
      "name":"Jhone",
      "username":"Jhone123",
     }

CodePudding user response:

There's a few ways to do this.

A simple example:

const express = require('express')
const app = express()
const port = 8080
var users = require('./users');

app.get('/user/:uid', (req, res) => {
  let foundUser = users.find(x => x.id === parseInt(req.params.uid));
  let jsonString = JSON.stringify(foundUser);
  res.send(jsonString);
});

app.listen(port, () => {
    console.log(`app listening at http://localhost:${port}`)
  });

You can do similar things with the Array.map() function as well.

  • Related