martianwars
martianwars

Reputation: 6500

Pretty printing JSON to a file in Node

So I have a very large JSON data which I am sending to a node server via AngularJS. This is the procedure I'm using to send data :-

var send_data="data="+encodeURIComponent(JSON.stringify($scope.records,null,4));
            $http({ 
            method : 'POST', 
            url : 'http://localhost:8888/updateDetails', 
            data : send_data, 
            responseType : "json",
            headers: {
                "Content-Type": 'application/x-www-form-urlencoded'
            }
          }).success(function(data, status, headers, config){
                console.log(data);
          });

I successfully managed to send a pretty printed JSON to the Node Server via the above code. However when I write this to a file using :-

jsonfile.writeFile(file, JSON.parse(req['body']['data']), function (err) {
        console.error(err);
    });

After some testing I figured out that the error is in the JSON.parse statement. Any way to pretty print JSON to a file?

Upvotes: 3

Views: 4881

Answers (1)

brandonscript
brandonscript

Reputation: 73024

Use JSON.stringify(data[, replacer[, indent]]):

jsonfile.writeFile(file, JSON.stringify(JSON.parse(req.body.data), 0, 4), function (err) {
    console.error(err);
});

You also may or may not need to parse the response body though -- I believe responseType: "json" in the builder will automatically parse it for you:

jsonfile.writeFile(file, JSON.stringify(req.body.data, 0, 4), function (err) {
    console.error(err);
});

Here's a complete working isolated example of how it works:

var fs = require('fs');
var req = JSON.parse('{"body": {"data": "Some text."}}');
fs.writeFile('test.json', JSON.stringify(req.body, 0, 4), function (err) {

});

Assuming you're handling POST requests via an HTTP listener or framework like ? Are you using a body parser to parse the incoming JSON?

Let's try:

  1. console.log(req.body) to make sure your server recognizes the request.
  2. Is it a JSON string? Is it valid? Or is it a javascript object (i.e. already been parsed)?
  3. If it's been parsed, then my second suggestion will work. If it hasn't been parsed, parse it as I did in the first example.

Upvotes: 5

Related Questions