Extract variables from formatted string - javascript

I'm trying to see if there's something that exists to do the following. I'd hate to reinvent the wheel.
I have a string like this. It's a file name.
2014-12-22-thomas-javascript.md
I want to be able to provide a formatĀ for this schema.
{year}-{month}-{day}-{name}-{topic}.{extension}
And I'd like an object in return.
{
"year": "2014",
"month": "12",
"day": "22",
"name": "thomas",
"topic": "javascript",
"extension": "md"
}
This way of providing a string and a format is very reticent of these two functions from node core util, moment parse, and jekyll post names.
moment("12-25-1995", "MM-DD-YYYY");
util.format(format, [...])
jeykll post names

At the risk of reinventing a wheel;
String.parse = function parse() {
if(typeof arguments[0] === 'string' && typeof arguments[1] === 'string' ) {
var str = arguments[0];
var val = arguments[1];
var array = [], obj = {};
var re = /(?:{)([a-z]*)(?:})/gi;
var match, sre = str;
while(match = re.exec(str)) {
array.push(match[1]);
sre = sre.replace(match[0], '(\\w*)');
}
re = new RegExp(sre);
var matches = val.match(re);
if(matches) {
for(var i = 1; i < matches.length; i++) {
obj[array[i-1]] = matches[i];
}
}
return obj;
}
}
No doubt there are a bunch of ways this will break but works with your example;
String.parse("{year}-{month}-{day}-{name}-{topic}.{extension}", "2014-12-22-thomas-javascript.md");
EDIT
And for performing the reverse;
String.format = function format() {
if (typeof arguments[0] === 'string') {
var s = arguments[0];
var re = /(?:{)(\d*)(?:})/gi;
var a, i, match, search = s;
while (match = re.exec(search)) {
for (i = 1; i < arguments.length; i++) {
a = parseInt(match[1]) + 1;
s = s.replace(match[0], typeof arguments[a] !== 'object' ? arguments[a] || '' : '');
}
}
re = /(?:{)([a-z]*)(?:})/gi;
match, search = s;
while (match = re.exec(search)) {
for (i = 1; i < arguments.length; i++) {
if (arguments[i].hasOwnProperty(match[1])) {
s = s.replace(match[0], arguments[i][match[1]]);
}
}
}
return s;
}
}
Which can accept named object members or positional for non-objects.
String.format("{0}-{name}{1}-{year}-{src}", 20, "abc", { name: "xyz", year: 2014 }, { src: 'StackOverflow' });
20-xyzabc-2014-StackOverflow

I found the code in Hexo, it's like jekyll but built with node.
var Permalink = require('hexo-util').Permalink;
var permalink = new Permalink(':year-:month-:day-:name-:topic.:extension
', {
segments: {
year: /(\d{4})/,
month: /(\d{2})/,
day: /(\d{2})/
}
});
permalink.parse('2014-12-22-thomas-javascript.md');
// {year: 2014, month: 12, day: 22, ...}

Related

i couldn't figure out how can i make the object dynamically

as you can see i get the "p" array from a html form, and i want to make a dynamic object from the "p" array here
function filter(p){
var obj;
console.log(p);//[ 'Grade', '>','123']
if(p[1]== ">"){p[1]=gt}
obj = {
$and:[
{p[0]: {$p[1]: p[3}}
]
}
return obj;
}
to pass it to this aggregation function:
async function query(DS,filter,q1,q2,q3){
arr.length = 0;
var obj;
var x = [];
var y = [];
var filtered;
const projection = { _id: 0 }; projection[q1] = 1; projection[q2] = 1;
const grouping ={}; grouping[q1]=q1; grouping[q2] = q2;
filtered = await DS.aggregate([
{$project: projection},
{$match: filter}
]).toArray()
}
if(q3 == ""){
for (let i = 0; i < filtered.length; i++) {
obj = filtered[i]
x.push(obj[q1])
y.push(obj[q2])
}
arr.push(x)
arr.push(y)
return arr;
}
i couldn't figure out how can i make the object dynamically.
If you want to generate the objects keys dynamically, you can compute them by using square brackets where the key(s) would go.
For your case, you can replace this:
if(p[1]== ">"){p[1]=gt}
obj = {
$and:[
{p[0]: {$p[1]: p[3}}
]
}
with this:
if (p[1] === ">") { p[1] = 'gt' }
obj = {
$and:[
{
[p[0]]: {
['$' + p[1]]: p[2]
}
}
]
}
and you will get this object as a result (when using your provided input):
{"$and": [
{
"Grade": {
"$gt": "123"
}
}
]
}
Hope that helps!

Javascript Parsing Key Value String to JSON

I'm currently working on trying to create a UDF to split a key value pair string based on web traffic into JSON.
I've managed to get as far as outputting a JSON object but I'd like to be able to dynamically add nested items based on the number of products purchased or viewed based on the index number of the key.
When a product is only viewed, there is always only one product in the string. Only when its a transaction is it more than one but I think it would be good to conform the structure of the json and then identify a purchase or view based on the presence of a transactionid. For example:
Item Purchased:
sessionid=12345&transactionid=555555&product1=apples&productprice1=12&product1qty=1&product2=pears&productprice2=23&product2qty=3&transactionamount=58
The output should look something like this:
[
{
"sessionid":12345,
"transactionid":555555,
"transactionamount":58
},
[
{
"productline":1,
"product":"apples",
"productprice":12,
"productqty":1
},
{
"productline":2,
"product":"pears",
"productprice":23,
"productqty":2
}
]
]
Item Viewed:
sessionid=12345&product1=apples&productprice1=12&product1qty=1&product2=pears&productprice2=23&product2qty=3
[
{
"sessionid":12345,
"transactionid":0,
"transactionamount":0
},
[
{
"productline":1,
"product":"apples",
"productprice":12,
"productqty":1
}
]
]
The result I'll be able to parse from JSON into a conformed table in a SQL table.
What I've tried so far is only parsing the string, but its not ideal to create a table in SQL because the number of purchases can vary:
var string = "sessionid=12345&transactionid=555555&product1=apples&productprice1=12&product1qty=1&product2=pears&productprice2=23&product2qty=3&transactionamount=58";
function splitstring(queryString) {
var dictionary = {};
if (queryString.indexOf('?') === 0) {
queryString = queryString.substr(1);
}
var parts = queryString.split('&');
for (var i = 0; i < parts.length; i++) {
var p = parts[i];
// Step 2: Split Key/Value pair
var keyValuePair = p.split('=');
var key = keyValuePair[0];
var value = keyValuePair[1];
dec_val = decodeURIComponent(value);
final_value = dec_val.replace(/\+/g, ' ');
dictionary[key] = final_value;
}
return (dictionary);
}
console.log(splitstring(string));
Thanks in advance!!!
Feel like this would be less clunky with better param naming conventions, but here's my take...
function parseString(string) {
var string = string || '',
params, param, output, i, l, n, v, k, pk;
params = string.split('&');
output = [{},
[]
];
for (i = 0, l = params.length; i < l; i++) {
param = params[i].split('=');
n = param[0].match(/^product.*?([0-9]+).*/);
v = decodeURIComponent(param[1] || '');
if (n && n[1]) {
k = n[1];
output[1][k] = output[1][k] || {};
output[1][k]['productline'] = k;
pk = n[0].replace(/[0-9]+/, '');
output[1][k][pk] = v;
} else {
output[0][param[0]] = v;
}
}
output[1] = output[1].filter(Boolean);
return output;
}
var string = "sessionid=12345&transactionid=555555&product1=apples&productprice1=12&product1qty=1&product2=pears&productprice2=23&product2qty=3&transactionamount=58";
console.log(parseString(string));
output:
[
{
"sessionid": "12345",
"transactionid": "555555",
"transactionamount": "58"
},
[{
"productline": "1",
"product": "1",
"productprice": "12"
}, {
"productline": "2",
"product": "3",
"productprice": "23"
}]
]
There's probably a far nicer way to do this, but I just wrote code as I thought about it
var string = "sessionid=12345&transactionid=555555&product1=apples&productprice1=12&product1qty=1&product2=pears&productprice2=23&product2qty=3&transactionamount=58";
function splitstring(queryString) {
var dictionary = {};
if (queryString.indexOf('?') === 0) {
queryString = queryString.substr(1);
}
var parts = queryString.split('&');
for (var i = 0; i < parts.length; i++) {
var p = parts[i];
// Step 2: Split Key/Value pair
var keyValuePair = p.split('=');
var key = keyValuePair[0];
var value = keyValuePair[1];
dec_val = decodeURIComponent(value);
final_value = dec_val.replace(/\+/g, ' ');
dictionary[key] = final_value;
}
return (dictionary);
}
function process(obj) {
let i = 1;
const products = [];
while(obj.hasOwnProperty(`product${i}`)) {
products.push({
[`product`]: obj[`product${i}`],
[`productprice`]: obj[`productprice${i}`],
[`productqty`]: obj[`product${i}qty`]
});
delete obj[`product${i}`];
delete obj[`productprice${i}`];
delete obj[`product${i}qty`];
++i;
}
return [obj, products];
}
console.log(process(splitstring(string)));
By the way, if this is in the browser, then splitstring can be "replaced" by
const splitstring = string => Object.fromEntries(new URLSearchParams(string).entries());
var string = "sessionid=12345&transactionid=555555&product1=apples&productprice1=12&product1qty=1&product2=pears&productprice2=23&product2qty=3&transactionamount=58";
function process(string) {
const splitstring = queryString => {
var dictionary = {};
if (queryString.indexOf('?') === 0) {
queryString = queryString.substr(1);
}
var parts = queryString.split('&');
for (var i = 0; i < parts.length; i++) {
var p = parts[i];
// Step 2: Split Key/Value pair
var keyValuePair = p.split('=');
var key = keyValuePair[0];
var value = keyValuePair[1];
dec_val = decodeURIComponent(value);
final_value = dec_val.replace(/\+/g, ' ');
dictionary[key] = final_value;
}
return (dictionary);
};
let i = 1;
const obj = splitstring(string);
const products = [];
while (obj.hasOwnProperty(`product${i}`)) {
products.push({
[`product`]: obj[`product${i}`],
[`productprice`]: obj[`productprice${i}`],
[`productqty`]: obj[`product${i}qty`]
});
delete obj[`product${i}`];
delete obj[`productprice${i}`];
delete obj[`product${i}qty`];
++i;
}
return [obj, products];
}
console.log(process(string));

Javascript: Parse array like search querystring

This is a string i have in my javascript
var searchString = City=20&Region=67&&Interests[8]=8&Interests[13]=13&Interests[4]=4&Duration[1]=Full+Day+Tour&Duration[3]=Evening+Tour&Duration[5]=2+Day+Short+Break&Departs[Fri]=Fri&Departs[Sat]=Sat&Departs[Sun]=Sun&TourLanguages=1&action_doSearch=Update
and i have a function
function loadDataFrom(request){
//if request if empty then return
if(request == "")
return;
var request = decodeURIComponent(request);
//if we get there then its likely we have a search query to process
var searchCriteria = request.split('&');
var hash = {};
for(var i = 0; i < searchCriteria.length; i++) {
var val = searchCriteria[i].split('=');
//we can safely ignore the "view" and 'action_doSearch' becuase they are not searched on
if(unescape(val[0]) === 'view' || unescape(val[0]) === 'action_doSearch')
continue;
//filter objects without any values
if(val[1] != '')
//add the names and values to our object hash
hash[unescape(val[0])] = unescape(val[1]);
}
//iterate over the hash objects and apply the current selection
$.each(hash, function(index, value) {
switch (index) {
case 'City':
case 'Region':
case 'TourLanguages':
//do stuff;
break;
case 'Duration[]':
case 'Departs[]':
//do something esle
default:
break;
}
});
};
that parses the URL parameters into an objecct hash with the following values.
City: "20"
Region: "67"
Departs[Fri]: "Fri"
Departs[Sat]: "Sat"
Departs[Sun]: "Sun"
Duration[1]: "Full+Day+Tour"
Duration[3]: "Evening+Tour"
Duration[5]: "2+Day+Short+Break"
Interests[4]: "4"
Interests[8]: "8"
Interests[13]: "13"
TourLanguages: "1"
but what i'd really like to do is to seperate the url into array like values like so
City: "20"
Region: "67"
Departs: ["Fri","Sat","Sun"]
Duration: ["Full+Day+Tour", "Evening+Tour", "2+Day+Short+Break"]
Interests: ["4", "8", "13"]
TourLanguages: "1"
Any help/pointers on this problem is greatly appreciated. Thanks in Advance
For something like this, to make it easier on myself I would write a RegExp to get the parts, then do some if logic to decide how to construct the Object.
var searchString = "City=20&Region=67&&Interests[8]=8&Interests[13]=13&Interests[4]=4&Duration[1]=Full+Day+Tour&Duration[3]=Evening+Tour&Duration[5]=2+Day+Short+Break&Departs[Fri]=Fri&Departs[Sat]=Sat&Departs[Sun]=Sun&TourLanguages=1&action_doSearch=Update",
o = {};
('&' + searchString)
.replace(
/&([^\[=&]+)(\[[^\]]*\])?(?:=([^&]*))?/g,
function (m, $1, $2, $3) {
if ($2) {
if (!o[$1]) o[$1] = [];
o[$1].push($3);
} else o[$1] = $3;
}
);
o; /*
{
"City": "20",
"Region": "67",
"Interests": ["8", "13", "4"],
"Duration": ["Full+Day+Tour", "Evening+Tour", "2+Day+Short+Break"],
"Departs": ["Fri", "Sat", "Sun"],
"TourLanguages": "1",
"action_doSearch": "Update"
} */
I would do it this way:
var str = 'City=20&Region=67&&Interests[8]=8&Interests[13]=13&Interests[4]=4&Duration[1]=Full+Day+Tour&Duration[3]=Evening+Tour&Duration[5]=2+Day+Short+Break&Departs[Fri]=Fri&Departs[Sat]=Sat&Departs[Sun]=Sun&TourLanguages=1&action_doSearch=Update',
strsplit = str.split(/&+/),
o = {};
for (var i = 0, l = strsplit.length; i < l; i++) {
var r = strsplit[i].match(/^([^=\[\]]+)(?:\[[^\]]+\])?=(.*)$/);
if (o[r[1]] === undefined) {
o[r[1]] = r[2];
} else if (o[r[1]].push) {
o[r[1]].push(r[2]);
} else {
o[r[1]] = [o[r[1]], r[2]];
}
}
This is a perfect scenario to use Map-Reduce and I recommend you to use underscore.js to implement something simple, elegant and more readable solution.
var m = _.map(searchString.split('&'), function (item) {
var parts = item.split('='), names = parts[0].split('[');
return [names[0], parts[1]];
});
var result = _.reduce(m, function(memo, item){
var key = item[0], value = item[1];
if(memo[key] === undefined) memo[key] = [value]
else memo[key].push(value)
return memo;
}, {});
console.log(result);

JSON.stringify whitelisting with nested objects

Given following example:
var test = {
"company_name": "Foobar",
"example": "HelloWorld",
"address": {
"street": "My Street 12",
"example": "BarFoo",
"details": "Berlin",
}
}
console.log(JSON.stringify(test, ['company_name','address','street','example']));
// What I actually want
// console.log(JSON.stringify(test, ['company_name','address.street','address.example']));
How can I use JSON's stringify function to deal with nested objects properly?
Since I have huge JSON objects it happens that a key of a nested object is identical to it's "parent" object. I would like to specify my whitelist more granulary.
If you're willing to go to the effort of whitelisting, then you can establish an array of valid keys, which can provide the ability to nest similar to how many systems do JSON nesting (a . separator, or any separator of your choosing).
var whitelistedObj = whitelistJson(obj, ["company_name", "example", "address.street", "address.example"]);
function whitelistJson(obj, whitelist, separator) {
var object = {};
for (var i = 0, length = whitelist.length; i < length; ++i) {
var k = 0,
names = whitelist[i].split(separator || '.'),
value = obj,
name,
count = names.length - 1,
ref = object,
exists = true;
// fill in any empty objects from first name to end without
// picking up neighboring fields
while (k < count) { // walks to n - 1
name = names[k++];
value = value[name];
if (typeof value !== 'undefined') {
if (typeof object[name] === 'undefined') {
ref[name] = {};
}
ref = ref[name];
}
else {
exists = false;
break;
}
}
if (exists) {
ref[names[count]] = value[names[count]];
}
}
return object;
}
I have a JSFiddle showing its usage as well (to ensure it actually worked on my admittedly small sample set).
You can add toJSON method in your huge JSON objects:
var test = {
"company_name": "Foobar",
"example": "HelloWorld",
"address": {
"street": "My Street 12",
"example": "BarFoo",
"details": "Berlin",
},
toJSON: function () {
return {
company_name: this.company_name,
address: {
street: this.address.street,
example: this.address.example
}
}
}
}
And, you get:
console.log(JSON.stringify(test)); // "{"company_name":"Foobar","address":{"street":"My Street 12","example":"BarFoo"}}"
Or, you can use some filter function: (this function using lodash)
function filter(object, keys, sep) {
sep = sep || '.';
var result = {};
_.each(keys, function (key) {
var keyParts = key.split(sep),
res = object,
branch = {},
branchPart = branch;
for (var i = 0; i < keyParts.length; i++) {
key = keyParts[i];
if (!_.has(res, key)) {
return;
}
branchPart[key] = _.isObject(res[key]) ? {} : res[key];
branchPart = branchPart[key];
res = res[key];
}
_.merge(result, branch);
});
return result;
}
console.log(JSON.stringify(filter(test, ['company_name', 'address.street', 'address.example']))); // "{"company_name":"Foobar","address":{"street":"My Street 12","example":"BarFoo"}}"
Check out jsfiddle http://jsfiddle.net/SaKhG/

How to convert an x-www-form-urlencoded string to JSON?

Exampple of application/x-www-form-urlencoded string
CorrelationId=1&PickedNumbers%5B%5D=1&PickedNumbers%5B%5D=2&PickedNumbers%5B%5D=3&PickedNumbers%5B%5D=4
Into JSON
var gamePlayData = {
CorrelationId: gameId,
PickedNumbers: ["1","2","3","4"]
};
This is a core module of Node.js now: https://nodejs.org/api/querystring.html#querystring_querystring_parse_str_sep_eq_options
var qs = require('querystring')
var json = qs.parse('why=not&sad=salad')
// { why: 'not', sad: 'salad' }
Works with encoded characters too:
var json2 = qs.parse('http%3A%2F%2Fexample.com&sad=salad')
// { url: 'http://example.com', sad: 'salad' }
I've been dealing with this recently: I had to parse data that could contain objects nested up to 5 levels deep. I needed the code to be able to deal with both rather complex data, but not fail to decode a URI as simple as id=213.
I spent quite some time on google, trying to find a (semi-)elegant solution to this problem, and this question kept showing up. Since it gets 1 view/day (give or take) I've decided to post my solution here, hope it helps someone out:
function form2Json(str)
{
"use strict";
var obj,i,pt,keys,j,ev;
if (typeof form2Json.br !== 'function')
{
form2Json.br = function(repl)
{
if (repl.indexOf(']') !== -1)
{
return repl.replace(/\](.+?)(,|$)/g,function($1,$2,$3)
{
return form2Json.br($2+'}'+$3);
});
}
return repl;
};
}
str = '{"'+(str.indexOf('%') !== -1 ? decodeURI(str) : str)+'"}';
obj = str.replace(/\=/g,'":"').replace(/&/g,'","').replace(/\[/g,'":{"');
obj = JSON.parse(obj.replace(/\](.+?)(,|$)/g,function($1,$2,$3){ return form2Json.br($2+'}'+$3);}));
pt = ('&'+str).replace(/(\[|\]|\=)/g,'"$1"').replace(/\]"+/g,']').replace(/&([^\[\=]+?)(\[|\=)/g,'"&["$1]$2');
pt = (pt + '"').replace(/^"&/,'').split('&');
for (i=0;i<pt.length;i++)
{
ev = obj;
keys = pt[i].match(/(?!:(\["))([^"]+?)(?=("\]))/g);
for (j=0;j<keys.length;j++)
{
if (!ev.hasOwnProperty(keys[j]))
{
if (keys.length > (j + 1))
{
ev[keys[j]] = {};
}
else
{
ev[keys[j]] = pt[i].split('=')[1].replace(/"/g,'');
break;
}
}
ev = ev[keys[j]];
}
}
return obj;
}
I've tested it, with data like the string below (4 levels deep):
str = "id=007&name[first]=james&name[last]=bond&name[title]=agent&personalia[occupation]=spy&personalia[strength]=women&personalia[weakness]=women&tools[weapons][close][silent]=garrot&tools[weapons][medium][silent]=pistol_supressed&tools[weapons][medium][loud]=smg&tools[weapons][far][silent]=sniper&tools[movement][slow]=foot&tools[movement][far]=DBS";
Which neatly returns an object, that, when passed through JSON.stringify comes out like this:
{"id":"007","name":{"title":"agent","first":"james","last":"bond"},"personalia":{"weakness":"women","occupation":"spy","strength":"women"},"tools":{"movement":{"far":"DBS","slow":"foot"},"weapons":{"close":{"silent":"garrot"},"medium":{"silent":"pistol_supressed","loud":"smg"},"far":{"silent":"sniper"}}}}
It passes a JSlint check, when ignoring white space, . and [^...] and accepting ++. All in all, I'd consider that to be acceptable.
You can use qs if you're using node, or browserify.
var qs = require('qs')
var encodedString = "CorrelationId=1&PickedNumbers%5B%5D=1&PickedNumbers%5B%5D=2&PickedNumbers%5B%5D=3&PickedNumbers%5B%5D=4"
console.log(qs.parse(encodedString))
// { CorrelationId: '1', PickedNumbers: [ '1', '2', '3', '4' ] }
the following code should do the trick:
var str = 'CorrelationId=1&PickedNumbers%5B%5D=1&PickedNumbers%5B%5D=2&PickedNumbers%5B%5D=3&PickedNumbers%5B%5D=4';
var keyValuePairs = str.split('&');
var json = {};
for(var i=0,len = keyValuePairs.length,tmp,key,value;i <len;i++) {
tmp = keyValuePairs[i].split('=');
key = decodeURIComponent(tmp[0]);
value = decodeURIComponent(tmp[1]);
if(key.search(/\[\]$/) != -1) {
tmp = key.replace(/\[\]$/,'');
json[tmp] = json[tmp] || [];
json[tmp].push(value);
}
else {
json[key] = value;
}
}
Updated answer for 2022, works both in the browser and in node.
Use URLSearchParams class.
Note: The param name PickedNumbers%5B%5D will turn to be the literal string PickedNumbers[]. You don't need to encode the brackets in order to make it an array
const paramsStr = 'CorrelationId=1&PickedNumbers%5B%5D=1&PickedNumbers%5B%5D=2&PickedNumbers%5B%5D=3&PickedNumbers%5B%5D=4';
const params = new URLSearchParams(paramsStr);
//access a specific param
console.log(params.get('PickedNumbers[]')); // '4'
console.log(params.getAll('PickedNumbers[]')); // ['1','2','3','4']
const o = Object.fromEntries(Array.from(params.keys()).map(k => [k, params.getAll(k).length===1 ? params.get(k) : params.getAll(k)]));
console.log(JSON.stringify(o)); //full object
Here's a pure-JavaScript way to do it. JavaScript frameworks might also help you out with this. EDIT: Just for kicks, I threw in dictionary parsing, too. See the 2nd example.
function decodeFormParams(params) {
var pairs = params.split('&'),
result = {};
for (var i = 0; i < pairs.length; i++) {
var pair = pairs[i].split('='),
key = decodeURIComponent(pair[0]),
value = decodeURIComponent(pair[1]),
isArray = /\[\]$/.test(key),
dictMatch = key.match(/^(.+)\[([^\]]+)\]$/);
if (dictMatch) {
key = dictMatch[1];
var subkey = dictMatch[2];
result[key] = result[key] || {};
result[key][subkey] = value;
} else if (isArray) {
key = key.substring(0, key.length-2);
result[key] = result[key] || [];
result[key].push(value);
} else {
result[key] = value;
}
}
return result;
}
decodeFormParams("CorrelationId=1&PickedNumbers%5B%5D=1&PickedNumbers%5B%5D=2&PickedNumbers%5B%5D=3&PickedNumbers%5B%5D=4");
// => {"CorrelationId":"1","PickedNumbers":["1","2","3","4"]}
decodeFormParams("a%5Bb%5D=c&a%5Bd%5D=e");
// => {"a":{"b":"c","d":"e"}}
Try this->
// convert string to object
str = 'a=6&id=99';
var arr = str.split('&');
var obj = {};
for(var i = 0; i < arr.length; i++) {
var bits = arr[i].split('=');
obj[bits[0]] = bits[1];
}
//alert(obj.a);
//alert(obj.id);
// convert object back to string
str = '';
for(key in obj) {
str += key + '=' + obj[key] + '&';
}
str = str.slice(0, str.length - 1);
alert(str);
Or use this (JQuery) http://api.jquery.com/jQuery.param/
A one-liner:
let s = 'a=1&b=2&c=3';
Object.fromEntries(
s.split('&')
.map(s => s.split('='))
.map(pair => pair.map(decodeURIComponent)))
// -> {a: "1", b: "2", c: "3"}
and if you want repeated parameters to be represented as arrays:
let s = 'a=1&b=2&c[]=3&c[]=4&c[]=5&c[]=6';
s
.split('&')
.map(s => s.split('='))
.map(pair => pair.map(decodeURIComponent))
.reduce((memo, [key, value]) => {
if (!(key in memo)) { memo[key] = value; }
else {
if (!(memo[key] instanceof Array))
memo[key] = [memo[key], value];
else
memo[key].push(value);
}
return memo;
}, {})
// -> {"a":"1","b":"2","c[]":["3","4","5","6"]}
You need the opposite of jQuery.param. One of the options is http://benalman.com/code/projects/jquery-bbq/examples/deparam/
var jsonMessage = "{\"".concat(message.replace("&", "\",\"").replace("=", "\":\"")).concat("\"}");
In typescript, works for me:
Use qs.parse to transform in object ParsedQs.
Use as unknow to implicit type unknow and before force convert to string.
Use JSON.parse to convert an string to object.
It was useful to use validations with Joi.
const payload = JSON.parse(JSON.stringify(qs.parse(request.body) as unknown as string));
Payload (cURL):
--data-urlencode 'notification=123-456123' \
--data-urlencode 'test=123456' \
--data-urlencode 'ajieoajeoa=Lorem ipsum'
Result:
{
notification: '123-456123',
test: '123456',
ajieoajeoa: 'Lorem ipsum'
}
public static void Main()
{
string str ="RESULT=0&PNREF=A10AABBF8DF2&RESPMSG=Approved&AUTHCODE=668PNI&PREFPSMSG=No Rules Triggered&POSTFPSMSG=No Rules Triggered";
var sr = str.Replace("&", "=");
string[] sp = sr.Split('=');
var spl = sp.Length;
int n = 1;
var ss = "{";
for (var k = 0; k < spl; k++)
{
if (n % 2 == 0)
{
if (n == spl)
{
ss += '"' + sp[k] + '"';
}
else
{
ss += '"' + sp[k] + '"' + ",";
}
}
else
{
ss += '"' + sp[k] + '"' + ":";
}
n++;
}
ss += "}";
Console.WriteLine(ss);
}

Categories

Resources