Json Convert to and from query string with jquery?

I have a type string a=6&id=99(I can save it in html as "a = 6 & id = 99", but this is not what js will see). I would like to convert this string to an object so that I can execute func (oa); or o.id = 44; How to do it?

Part 2: How to convert this object back to the query string? it will probably be trivial code that I can write.

+5
source share
2 answers

You can use jQuery.param .

+12
source
// convert string to object
str = 'a=6&id=99';
var arr = str.split('&');
var obj = {};
for(var i = 0; i < arr.length; i++) {
    var bits = arr[i].split('=');
    obj[bits[0]] = bits[1];
}
//alert(obj.a);
//alert(obj.id);

// convert object back to string
str = '';
for(key in obj) {
    str += key + '=' + obj[key] + '&';
}
str = str.slice(0, str.length - 1); 
alert(str);

Try it here: http://jsfiddle.net/DUpQA/1/

+11
source

All Articles