5

I have a string like a=6&id=99 (i might store it in html as 'a=6&id=99' however thats not what js will see). I would like to convert that string into an object so i can do func(o.a); or o.id=44; How do i do that?

Part 2: How do i convert that object back to a query string? it would probably be trivial code that i can write.

2 Answers 2

12

You can use jQuery.param.

Sign up to request clarification or add additional context in comments.

Comments

11
// 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/

1 Comment

You would need to make this function recursive to deal with all JSON objects?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.