Search code examples
javascriptarraysjsonserializationserializearray

How to convert serialize array value to JSON in javascript


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());

Solution

  • 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>