Reputation: 5776
i have serialize array like this
rate_3=26&rate_8=67&rate_12=98
etc..,
now i need to change this array as json type
{
"ID": "3",
"Rate": "26"
},
{
"ID": "8",
"Rate": "67"
},
{
"ID": "3",
"Rate": "26"
} ..,
etc
so i tried like this but its not working... please some one help me.
var o = {};
var a = table.$('input, select').serialize();
$.each(a, function()
{
if (o[this.name] !== undefined)
{
if (!o[this.name].push)
{
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
}
else
{
o[this.name] = this.value || '';
}
});
return o;
i m using datatable so i just need to get Datatables serialize array only for that used this line
var a = table.$('input, select').serialize();
even i tried with json2.js also but when i use json2.js it forcing the page to submit
var data_2 = JSON.stringify(block_form.serializeArray());
Upvotes: 0
Views: 2224
Reputation: 63587
Simple method is to map
over the results of a regex match, pushing new objects into the resulting array:
var out = str.match(/\d+=\d+/g).map(function (el) {
var arr = el.split('=');
return { id: arr[0], rate: arr[1] };
});
Convert the output array to JSON with JSON.stringify(out)
.
Upvotes: 2
Reputation: 48337
If your data format is reliably in the rate_N=X&
format, you can use simple string splitting to parse out the values. This appears to be similar to how query strings are formatted and, if that's the case, you shouldn't run into (m)any unusual entities.
First, you'll want to break each key-value pair apart (on the &
). Then split each pair on the =
to produce the key and value. You'll need to parse the ID out of the key (cut the rate_
off the front), which substr will work well for.
var data = "rate_3=26&rate_8=67&rate_12=98";
var pairs = data.split('&').reduce(function(collect, pair) {
var kv = pair.split('=');
var name = kv[0].substr(kv[0].indexOf('_') + 1);
collect.push({
id: name,
rate: kv[1]
});
return collect;
}, []);
document.getElementById('results').textContent = JSON.stringify(pairs);
<pre id="results"></pre>
Upvotes: 1
Reputation: 5776
var str = 'rate_3=26&rate_8=67&rate_12=98'
var arr = str.split('&').map(function(element) {
return element.replace(/^rate_/, '');
}).map(function(element) {
var elements = element.split('=');
return {
"ID" : elements[0],
"Rate" : elements[1]
};
});
console.log(arr);
Upvotes: 0