简体   繁体   中英

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 ?

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 !

You could iterate thru your list that you are sending, enclose comma inside a string with double quotes. Then handle those double quotes on the server side. This will preserve your list integrity

use something like this to replace subString:

str = str.replace(/,/g, '","');

On the serverSide, you can then ignore all commas wrapped inside double quotes.

尝试

var namesList = arrayNames.map(function(val) { return val.replace(',', '\\,');}).toString();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM