Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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-

This comment has been minimized.

Copy link
Owner 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

This comment has been minimized.

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

This comment has been minimized.

Copy link

sanchezzzhak commented Dec 6, 2017

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

This comment has been minimized.

Copy link

akinozgen commented Oct 8, 2018

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'}));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.