Get hands-on experience with 20+ free Google Cloud products and $300 in free credit for new customers.

Append of JSON to the payload

Hi,

I am reading through different files in an loop.Now I need to add the content of all files(JSON) and send the payload.

But I am getting the output as below with {} appended in the front and \ in the results.

{}{\"Complexity\":[\"Medium\",\"Low\",\"High\"]}"{"color":["Red","Blue","Green"]}

Below is the code:

'use strict';
const fs = require('fs');
var http = require('http');
var url = require('url');
var path = require("path");
var payload = {};
function requestHandler(request, response) {
  var files =[file1.json,file2.json]
  for(item in files){
    filename =files[item];
    if(item=== 0)
    {
      payload = JSON.parse(fs.readFileSync(filename, 'utf-8'));
    }
    else
    {
      filecontent = JSON.parse(fs.readFileSync(filename, 'utf-8'));
      payload = JSON.stringify(payload).concat(JSON.stringify(filecontent));
    }
  }
  response.writeHead(200, {"Content-Type": "application/json"});
  response.end(JSON.stringify(payload, null, 2) + '\n');
}


var svr = http.createServer(requestHandler);
svr.listen(9000, function() {
  console.log('Node HTTP server is listening');
});

Expected output is without {} in the front and without \ in the results.

I also tried using stringbuffer as below but got an error that it could not find string buffer in Apigee

	var StringBuffer =require("stringbuffer");
Solved Solved
0 3 1,397
1 ACCEPTED SOLUTION

You can implement the same thing without the if/else condition to avoid duplicating your fileread/parse line

If you're wanting to return a valid json structure where the content of each file is returned in a combined json array it would be something like...

var fileItems = [];
for (i in files) {
	var filename = files[i];
	var fileJson = JSON.parse(fs.readFileSync(filename, 'utf-8'));
	fileItems.push(fileJson);
}


// your response building code here, using stringify only once
// JSON.stringify(fileItems)

View solution in original post

3 REPLIES 3