Reputation: 6500
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
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 express? Are you using a body parser to parse the incoming JSON?
Let's try:
console.log(req.body)
to make sure your server recognizes the request.Upvotes: 5