Skip to content

Instantly share code, notes, and snippets.

@luk-
Created May 17, 2012 22:42
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save luk-/2722097 to your computer and use it in GitHub Desktop.
Save luk-/2722097 to your computer and use it in GitHub Desktop.
php's http_build_query() in javascript
var build_query = function (obj, num_prefix, temp_key) {
var output_string = []
Object.keys(obj).forEach(function (val) {
var key = val;
num_prefix && !isNaN(key) ? key = num_prefix + key : ''
var key = encodeURIComponent(key.replace(/[!'()*]/g, escape));
temp_key ? key = temp_key + '[' + key + ']' : ''
if (typeof obj[val] === 'object') {
var query = build_query(obj[val], null, key)
output_string.push(query)
}
else {
var value = encodeURIComponent(obj[val].replace(/[!'()*]/g, escape));
output_string.push(key + '=' + value)
}
})
return output_string.join('&')
}
@luk-
Copy link
Author

luk- commented May 17, 2012

var input = {
  cow: "moo",
  dog: "woof",
  4: "meow",
  pig: "oink",
  food: {
    beers: {
      bud: "shitty",
      guinness: "good"
    },
    pizza: "delicious"
  }
}


var query = build_query(input, 5)


console.log(query)

@craftpip
Copy link

craftpip commented Jul 5, 2017

This does not work with arrays,

build_query({
    data: '1',
    terms: [
        123,
        234,
    ]
});

Must give
?data=1&terms[0]=123&terms[1]=234

@sanchezzzhak
Copy link

tnx helper function

nodejs8.4

const querystring = require('querystring');
/** @see https://gist.github.com/luk-/2722097 */
exports.buildQuery = function (obj, numPrefix, tempKey) {
    let output_string = [];
    Object.keys(obj).forEach(function (val) {
        let key = val;
        numPrefix && !isNaN(key) ? key = numPrefix + key : '';
        key = encodeURIComponent(String(key).replace(/[!'()*]/g, querystring.escape));
        tempKey ? key = tempKey + '[' + key + ']' : '';

        if (typeof obj[val] === 'object') {
            let query = exports.buildQuery(obj[val], null, key);
            output_string.push(query)
        }
        else {
            let value = encodeURIComponent(String(obj[val]).replace(/[!'()*]/g, querystring.escape));
            output_string.push(key + '=' + value)
        }
    });
    return output_string.join('&')
};

@akinozgen
Copy link

for just key value pairs.

function http_build_query(jsonObj) {
  const keys = Object.keys(jsonObj);
  const values = keys.map(key => jsonObj[key]);

  return keys
    .map((key, index) => {
      return `${key}=${values[index]}`;
    })
    .join("&");
};

console.log(http_build_query({username: 'asd', password: '1234'}));

@droidmanspace
Copy link

droidmanspace commented Nov 19, 2020

Does


function http_build_query (obj, num_prefix , temp_key) {

    let output_string = [];
    Object.keys(obj).forEach(function (val) {
        let key = val;
        num_prefix  && !isNaN(key) ? key = num_prefix  + key : '';
        key = encodeURIComponent(String(key).replace(/[!'()*]/g, querystring.escape));
        temp_key ? key = temp_key + '[' + key + ']' : '';

        if (typeof obj[val] === 'object') {
            let query = http_build_query(obj[val], null, key);
            output_string.push(query);
        }
        else {
            let value = encodeURIComponent(String(obj[val]).replace(/[!'()*]/g, querystring.escape));
            output_string.push(key + '=' + value)
        }
    });
    return output_string.join('&')
  
  }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment