Turn serialized inputs into JSON

Asked

Viewed 161 times

0

In a datatable there are some columns with inputs. If you click the Submit button I will serialize the inputs of the lines that have checkbox marked. The return of the serialize:

'id=1596&inputCodPag=dwad&inputDtPagto=22-03-2018&inputDtMalote=&inputTpPagamento=BB&id=2045&inputCodPag=dwad&inputDtPagto=&inputDtMalote=&inputTpPagamento=SAP'

What I want to know is, how do you turn this into a JSON? The ideal would be to maintain in the following structure:

[{id:1596,inputCodPag:dwad,inputDtPagto:'22-03-2018',inputDtMalote:'',inputTpPagamento:'BB'},{id:2045, inputCodPag:'dwad', inputDtPagto:''.inputDtMalote:'',inputTpPagamento:'SAP'}]

Thank you.

  • are very different things... how about starting by separating the string with split("&"), read each value and mount the object?

1 answer

2

I don’t think you have anything native to it, but you can use this function...

function deparam(query) {
    var pairs, i, keyValuePair, key, value, map = {};
    // remove leading question mark if its there
    if (query.slice(0, 1) === '?') {
        query = query.slice(1);
    }
    if (query !== '') {
        pairs = query.split('&');
        for (i = 0; i < pairs.length; i += 1) {
            keyValuePair = pairs[i].split('=');
            key = decodeURIComponent(keyValuePair[0]);
            value = (keyValuePair.length > 1) ? decodeURIComponent(keyValuePair[1]) : undefined;
            map[key] = value;
        }
    }
    return map;
}

let resul = deparam('id=1596&inputCodPag=dwad&inputDtPagto=22-03-2018&inputDtMalote=&inputTpPagamento=BB&id=2045&inputCodPag=dwad&inputDtPagto=&inputDtMalote=&inputTpPagamento=SAP');

console.log(JSON.stringify(resul));

Source: https://stackoverflow.com/questions/6992585/jquery-deserialize-form#8918929

  • Oops! Thanks for the reply, this works great!! There is only one thing, as in the example I gave, that I serialized two table rows (2 id’s), your Function considered only the last, id=2045. Is there a way to make this Function more flexible? In case it will always be the same fields, but I can give the Submit in 50 lines.

  • Well, I think this is not possible, because the 'id' key comes from the 'name' property of the form field, that is, it is an identifier attribute that cannot be repeated, another issue is that the function converts to object before converting to JSON, and an object also does not accept 2 equal keys... if the answer has helped you, it is interesting to accept it in the upper left corner...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.