-1

I have a need of transforming various message formats into JSON and v.v., e.g. XML to JSON and then JSON to XML or EDI to JSON and JSON to EDI.

I've looked at several different XML-to-JSON modules and they seem mostly to be into a direct conversion into their own JSON and/or XML format and not into my required XML (e.g. UBL 2.1).

One easy straight forward way of going about it is to just use a String variable:

let myXML = '<root><hdr>' + jsonIn.hdr + '</hdr>\r\n';
myXML += '<itm>' + jsonIn.item[0] + '</hdr></root>';

The myXML variable will be quite big though. Up to 200 kB currently but can grow bigger in the future.

Obviously this is the quickest and easiest way of creating the outbound formats but it doesn't really feel right to create a massive String variable...

In Java I'd use StringBuilder and there is a npm for Node: https://www.npmjs.com/package/stringbuilder

Which approach would you consider the "best practice" approach?

Anders
  • 3,198
  • 1
  • 20
  • 43
  • 1
    What do you do with the transformed result? That seems fairly essential to determining a correct solution. – T.J. Crowder Jan 17 '17 at 15:19
  • Sorry if a bit unclear... The transformed result is either pushed to a AWS SQS queue to be picked up from AWS API Gateway or placed as a file in AWS S3 where it is accessible from a SFTP server. – Anders Jan 17 '17 at 16:08
  • See: https://stackoverflow.com/questions/13859543/fast-way-to-concatenate-strings-in-nodejs-javascript – marciowb Feb 17 '20 at 15:11

1 Answers1

0

In Java I'd use StringBuilder...

If that's the case and so you do in the end need to end up with a single string containing the result, a fairly normal pattern is to build up the individual strings in an array, and then use Array#join when you're done to produce that one big final string:

let myXML = [];
myXML.push('<root><hdr>' + jsonIn.hdr + '</hdr>\r\n');
myXML.push('<itm>' + jsonIn.item[0] + '</hdr></root>');
// ...

// When you're ready for the big string:
myXML = myXML.join("");

If you don't need a big string at the end, but are writing to a file, etc., writing as you go would tend to be a good solution.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • Ok, thanks, pretty much as I figured then... I don't write to a file, it's being pushed out as a HTTP POST. – Anders Jan 17 '17 at 16:10