Andrew Wei
Andrew Wei

Reputation: 2080

How convert URI parameters into JSON

I have a params string:

program_id=11792&percentage=5

I want it converted it to standard JSON:

{"program_id":"117902", "percentage":"5"}

Upvotes: 2

Views: 2795

Answers (4)

Greg Burghardt
Greg Burghardt

Reputation: 1

I wrote a general purpose solution if you're interested:

https://github.com/gburghardt/cerealizer

Upvotes: -1

Cristi Mihai
Cristi Mihai

Reputation: 2565

One liner:

var json = params.split('&').map(function(i) { return i.split('=');}).reduce(function(m,o){ m[o[0]] = o[1]; return m;},{});

A more complete solution:

params.split('&').map(function(i) { 
    return i.split('=');
}).reduce(function(memo, i) { 
    memo[i[0]] = i[1] == +i[1] ? parseFloat(i[1],10) : decodeURIComponent(i[1]); 
    return memo;
}, {});
  • will parse numbers:

    "no=2" => { no: 2 } compared to the previous version { no: "2" }.

  • will perform URI decoding:

    "greeting=hello%3Dworld" => { greeting: "hello world" }

Upvotes: 4

Scott Sauyet
Scott Sauyet

Reputation: 50787

var convert = function(params) {
    return params.split("&").map(function(item) {
        return item.split("=");
    }).reduce(function(obj, pair) {
        obj[pair[0]] = decodeURIComponent(pair[1]);
        return obj;
    }, {});
};

convert("program_id=11792&percentage=5&name=Andrew%20Wei");
//=> Object {program_id: "11792", percentage: "5", name: "Andrew Wei"}

You can call JSON.stringify on the resulting object if you want a string and not an object.

Upvotes: 0

Martin Majer
Martin Majer

Reputation: 3352

You can use this code, however, it doesn't check for any errors:

var url = "program_id=11792&percentage=5";
var parts = url.split("&");
var paramsObj = {};
for (var i = 0; i < parts.length; i++) {
   var keyAndValue = parts[i].split("=");
   paramsObj[keyAndValue[0]] = paramsObj[keyAndValue[1]];
}
console.log(paramsObj); // here's your object

Upvotes: 0

Related Questions