18

I am fairly new to JS and I have a JSON file that I need to send to my server (Express) that I can then parse and use its contents throughout the web app I'm building.

Here's what I have now:

  • a JSON file named data.json
  • an Express server set up that is running on a localhost
  • some shitty code:
    app.get('/search', function (req, res) {
     res.header("Content-Type",'application/json');
     res.send(JSON.stringify({/data.json/}));
    });

In the code above I am just trying to send the file to localhost:3000/search and see my JSON file, but all I receive when I go to that path is { }. Can anyone explain?

Any help would be immensely appreciated. Thanks so much in advance.

Cheers, Theo

Example snippet from data.json:

[{
    "name": "Il Brigante",
    "rating": "5.0",
    "match": "87",
    "cuisine": "Italian",
    "imageUrl": "/image-0.png"
}, {
    "name": "Giardino Doro Ristorante",
    "rating": "5.0",
    "match": "87",
    "cuisine": "Italian",
    "imageUrl": "/image-1.png"
}]
1

5 Answers 5

34

Just make sure you're requiring the correct file as a variable and then pass that variable into your res.send!

const data = require('/path/to/data.json')

app.get('/search', function (req, res) {
  res.header("Content-Type",'application/json');
  res.send(JSON.stringify(data));
})

Also, my personal preference is to use res.json as it sets the header automatically.

app.get('/search', function (req, res) {
  res.json(data);
})

EDIT:

The drawback to this approach is that the JSON file is only read once into memory. If you don't want the file read into memory or you're planning on modify the JSON on disk at some point then you should see Ian's Answer

Sign up to request clarification or add additional context in comments.

6 Comments

thanks so much! weirdly, the app.get function works, but it crashes whenever i put the `const data = require('src/data.json/'). any clue?
const data = require('./src/data.json')
Check your stack trace and see what it says and if it's locating the file. Remember that the require function starts looking in the directory in which the file it was called in is located, not the root of your application.
got it to work but now getting this error: "TypeError: path must be a string or Buffer". do you think the json file is formatted incorrectly? thanks for helping me again
Based on the sample you've supplied, your json is fine. This error may be coming from somewhere else in your application. Check the error stack trace for the line number and file that's causing it. It may be coming from improper usage of the fs (filesystem) module.
|
9

Another option is to use sendFile and set the content type header.

app.get('/search', (req, res) => {
    res.header("Content-Type",'application/json');
    res.sendFile(path.join(__dirname, 'file_name.json'));
})

The code assumes the file is in the same directory as the JS code. This answer explains how this works.

1 Comment

much better as we dont have to read the file first into memory
2

Try res.json(data.json) instead of res.send(...

6 Comments

thanks, but this doesn't solve my issue. Still getting "{ }". Is there a problem with my JSON do you think?
do a console.log(data.json) before sending it to see if it looks ok
it looks great! printing to terminal
So in the terminal it looks ok but when you navigate to the page you just see "{}" ?
exactly. really weird
|
0

Because __dirname resolves to where your script is running I prefer using path.resolve()

var path = require('path');

app.get('/search', (req, res) => {
    res.header("Content-Type",'application/json');
    res.sendFile(path.resolve('search/data.json'));
})

Comments

-1

Read the file first and then send the json to the client.

fs.readFile('file_name.json', 'utf8', function (err, data) {
  if (err) throw err;
  obj = JSON.parse(data);
  res.send(JSON.stringify(obj));
});

4 Comments

Hi! Thanks so much. I nested that in my app.get function. Is that what I should've done? Here is the code I have: app.get('/search', function (req, res) { app.readFile('data.json', 'utf8', function (err, data) { if (err) throw err; obj = JSON.parse(/data.json/); res.send(JSON.stringify(obj)); }); }); I am getting an error on the localhost saying app.readFile is not a function. Any clue why?
app.readFile won't work. You first have to add a require statement. var fs = require('fs'); Then use fs.readFile
hmm what's fs? should it be 'app'?
fs (File System) is a module included in Node

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.