How convert URI parameters into JSON

Andrew Wei

I have a params string:

program_id=11792&percentage=5

I want it converted it to standard JSON:

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

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" }

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related