ConfusedDeer
ConfusedDeer

Reputation: 3415

Sending back JSON?

How do I send back to the client the result (xml) that has been converted to a JSON object? I want to send the result back at line 168.

    153 var str= '';
    154
    155     callback = function(response) {
    156                                 //      var str = '';
    157
    158                                         //another chunk of data has been recieved, so append it to `str`
    159                                 response.on('data', function (chunk) {
    160                                         str += chunk;
    161                                                 } );
    162
    163                   //the whole response has been recieved, so we just print it out here
    164                                         response.on('end', function () {
    165                                         console.log("******************"+str+"*********************");
    166                                         var parseString = require('xml2js').parseString;
    167                                         //var xml = "<root>Hello xml2js!</root>"
    168                                         parseString(str, function (err, result) {
    169                                         console.dir(result);
    170                                         });
    171
    172                                 //      res.writeHead(200, {'Content-Type': 'text/plain'});
    173                                 //      res.write(str);
    174                                         });
    175                                    }
    176
    177                     
    178
    179                http.request(url, callback).end();
    180
    181
    182     //   console.log("---------------------"+str+"-----------------------------");
    183
    184
    185
    186   //      console.log(js2xmlparser("address",location));
    187
    188 //        res.write(str);
    189 res.end();
    190
    191
    192     }

Upvotes: 0

Views: 130

Answers (1)

dgiugg
dgiugg

Reputation: 1334

A little precision: there is no JSON Object, it is either an Object literal (a JS Object), either a JSON string. So your result is an Object. You will need to convert it to a JSON string, send it, and make your client convert it back to an Object. Write at line 169:

res.write(JSON.stringify(result));

Then in your client: JSON.parse(<responseString>) will be your response Object literal.

See https://www.npmjs.org/package/xml2js for more information.

Upvotes: 1

Related Questions