Viliami Viliami - 1 year ago 57
Javascript Question

How do I serialize an object for the query in a GET request?

I'm trying to serialize an object in JavaScript so that I can query it in a GET request.

Answer Source

The proper way, as per the standard, is:

function serialise(obj) {
    serialised = '';
    Object.keys(obj).forEach(function(key) {
        serialised += encodeURIComponent(key).replace(/%20/g, '+') + encodeURIComponent(obj[key]).replace(/%20/g, '+')
    return serialised;

var queryString = serialise({key: 'value', key2: 'value2'});

encodeURIComponent encodes the string safe for x-www-form-urlencoded except it replaces spaces with %20 rather than +, so a final .replace is needed.