How to read an external local JSON file in JavaScript?

前端 未结 22 2430
醉酒成梦
醉酒成梦 2020-11-22 02:53

I have saved a JSON file in my local system and created a JavaScript file in order to read the JSON file and print data out. Here is the JSON file:

{"res         


        
22条回答
  •  半阙折子戏
    2020-11-22 03:04

    1. First, create a json file. In this example my file is words.json

    [{"name":"ay","id":"533"},
    {"name":"kiy","id":"33"},
    {"name":"iy","id":"33"},
    {"name":"iy","id":"3"},
    {"name":"kiy","id":"35"},
    {"name":"kiy","id":"34"}]

    1. And here is my code i.e,node.js. Note the 'utf8' argument to readFileSync: this makes it return not a Buffer (although JSON.parse can handle it), but a string. I am creating a server to see the result...

    var fs=require('fs');
    var data=fs.readFileSync('words.json', 'utf8');
    var words=JSON.parse(data);
    var bodyparser=require('body-parser');
    console.log(words);
    var express=require('express');
    
    var app=express();
    
    var server=app.listen(3030,listening);
    
    function listening(){
    console.log("listening..");
    }
    app.use(express.static('website'));
    app.use(bodyparser.urlencoded({extended:false}));
    app.use(bodyparser.json());

    1. When you want to read particular id details you can mention the code as..

     app.get('/get/:id',function(req,res){
    	
    var i;
    		 
     for(i=0;i

    1. When you entered in url as localhost:3030/get/33 it will give the details related to that id....and you read by name also. My json file has simillar names with this code you can get one name details....and it didn't print all the simillar names

     app.get('/get/:name',function(req,res){
    	
    var i;
    		 
     for(i=0;i

    1. And if you want to read simillar name details, you can use this code.

    app.get('/get/name/:name',function(req,res){
    word = words.filter(function(val){
      return val.name === req.params.name;
    });
    res.send(word);
    			 
     console.log("success");
    	  
    });

    1. If you want to read all the information in the file then use this code below.

    app.get('/all',sendAll);
     
     function sendAll(request,response){
     response.send(words);
    
     }
     

提交回复
热议问题