Skip to content
Advertisement

how to “escape” a comma in a comma-separated list in a POST request?

EDIT : the API developer provided a solution by using another delimiter and specifying it in the request (see below my answer to my own question)


I am sending POST requests to a RESTful API, which require a comma-separated list of arguments :

var request = require('request-promise'); //promisified npm request

// the list of names is huge
// those names are stored in a MongoDB database
// the namesList is generated programmatically before the request
var namesList = "name1,name2,name3,name4"

var requestOptions = {
  method: 'POST',
  uri: 'https://myAPI/someEndPoint/',
  body: {
    key: myAccessKey,
    names: namesList
  },
  json: true
};

request(requestOptions)
.then( () => {_do_something_} );

It works fine for most of the names, but some of them contain a comma :

var arrayNames = ["foo bar", "barfoo", "stupid, comma", "dammit"];

// is converted by my code in :

var namesList = "foo bar,barfoo,stupid, comma, dammit";

This inevitably leads to a wrong list being sent to the API… So, is there a way to “escape” the faulty comma programmatically when I generate the list from the array ?

Advertisement

Answer

The long awaited answer from the API developer has arrived (sent an e-mail a while ago), and the solution is as simple as it is efficient : just use another delimiter :

var namesList = "name1;name2;name3;name4" // use ';' instead of ',' here...

var requestOptions = {
  method: 'POST',
  uri: 'https://myAPI/someEndPoint/',
  body: {
    key: myAccessKey,
    names: namesList,
    delimiter: ';' // and specify the delimiter there !
  },
  json: true
};

request(requestOptions)
.then( () => {_do_something_} );

I don’t know if the delimiter field is standard or specific to this API, but it works perfectly for my use case !

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement