简体   繁体   中英

Return Value based on Key in Node.js

I'm quite new to the world of JS and Node so this might seem like quite an easy thing to do, but it's something I just can't seem to get working.

Say I have the following json example in a json file

{
"0": "somestring1",
"1": "somestring2",
"2": "somestring3",
"3": "somestring4",
"4": "somestring5",
"5": "somestring6",
"6": "somestring7"
}

and in my server.js file I am loading the file like so

var fs = require('fs')

var parsedJson = fs.readFile('./jsonfile.json', function (err, data) 
{
  res.write(data);
  res.end();
})

hitting the server returns all of the json (as expected) but what I want to do is parse the file and return a single value based on a key, so something along the lines of:

for (var entry in data)
{
    if (entry.key == 0)
    {
      res.write(thing.value);
      //"somestring1" would be sent here
    }
}

How is this sort of thing done in JS/Node. Everything I have tried doesn't seem to work

Thanks!

Kris

Maybe something like this?

var http = require('http');
var fs = require('fs');

var data = JSON.parse(fs.readFileSync('data.json'));

var server = http.createServer(function(req, res) {
  var key = req.url.replace('/', '');
  var value = data[key];

  if (value) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end(value);
  } else {
    res.writeHead(404, {'Content-Type': 'text/plain'});
    res.end('Not Found');
  }
});

server.listen(1337, '127.0.0.1');

Then on the command line:

$ curl localhost:1337/1
somestring2

$ curl localhost:1337/x
Not Found

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM