15

I can't seem to find an answer to this question.. How can I convert a URL parameters string to JSON in javascript? I mean to ask if there is an in-built function like this or a one-liner that could do the job?

Example:

some=params&over=here => {"some":"params","over":"here"}

php_nub_qq
  • 15,199
  • 21
  • 74
  • 144
  • you using jquery ? if yes , try If you use jQuery, JSON.parse(this.yourURLString); or jQuery.parseJSON(this.yourURLString); – Satya Jul 05 '13 at 07:11
  • 2
    [This answer](http://stackoverflow.com/a/2880929/502381) returns the kind of object you want. – JJJ Jul 05 '13 at 07:16
  • Are you asking about a pure string to string conversion problem here? Or are using a JavaScript server like node.js and have parameters coming in that you want to turn into an object and then, presumably, to JSON? – Ray Toal Jul 05 '13 at 07:17
  • @RayToal I just found out that ajax pre-set data with ajaxSetup in jquery will be overwritten instead of added to a local ajax function data property if the given data is a url-type string instead of an object and I was looking for a simple way to convert that string into a json so that my default data won't be overwritten. I guess I'll just add a custom function that I've been suggested in the answers below. – php_nub_qq Jul 05 '13 at 07:34
  • Understood. Stapal's answer is fine and readable. If you are interested in one-liners, I added an answer just for fun. – Ray Toal Jul 05 '13 at 16:47

7 Answers7

26

You can create a method which will return JSON object

var params = getUrlVars('some=params&over=here');
console.log(params);

function getUrlVars(url) {
    var hash;
    var myJson = {};
    var hashes = url.slice(url.indexOf('?') + 1).split('&');
    for (var i = 0; i < hashes.length; i++) {
        hash = hashes[i].split('=');
        myJson[hash[0]] = hash[1];
        // If you want to get in native datatypes
        // myJson[hash[0]] = JSON.parse(hash[1]); 
    }
    return myJson;
}

Demo: http://jsfiddle.net/jAGN5/

Satpal
  • 132,252
  • 13
  • 159
  • 168
6

Try this :

var str = 'some1=param&some2=param2';

JSON.parse('{"' + decodeURI(str).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g,'":"').replace(/\s/g,'') + '"}')

// {some1: "param1", some2: "param2"}
John Slegers
  • 45,213
  • 22
  • 199
  • 169
1nstinct
  • 1,745
  • 1
  • 26
  • 30
2

If it is a one-liner you are after, the Underscore library has a pretty function called object, which takes an array of pairs and builds an object from it:

> _.object(["some","param"],["over","here"])
{some: "param", over: "here"} 

If you use Underscore, you can one-line the construction of an object from your query string as follows:

> var s = 'some=param&over=here';
> _.object(s.split('&').map(function(p){return p.split('=');}))
{some: "param", over: "here"}

Now if all you want is the JavaScript object, you are done. You said in your question that you wanted JSON, so the next step is pretty easy:

> JSON.stringify(_.object(s.split('&').map(function(p){return p.split('=');})))
"{\"some\": \"param\", \"over\": \"here\"}"

Here is a live demo

If you are not using Underscore, you can always write a utility function of your own.

This one line is a little ugly, but Firefox 22 has some of the upcoming ES6 features like array comprehensions and arrows, so the code can be made even more compact in the future, e.g.

JSON.stringify(_.object(s.split('&').map(p => p.split('='))))

or even

JSON.stringify(_.object([p.split('=') for (p of s.split('&'))]))

Or maybe just stick to the readable for loops and make your own function. :)

Ray Toal
  • 86,166
  • 18
  • 182
  • 232
1

Try use this function:

// Returns an object with elements "name: value" with data ftom URL (the "name=value" pairs)
function getDataUrl(url) {
 // From: http://coursesweb.net/javascript/
  var url_data = url.match(/\?([^#]*)/i)[1];          // gets the string between '?' and '#'

  // separate the data into an array, in case the are multiple pairs name=value
  var ar_url_data = url_data.split('&');

  // traverse the array, and adds into an object elements name:value
  var data_url = {};
  for(var i=0; i<ar_url_data.length; i++) {
    var ar_val = ar_url_data[i].split('=');           // separate name and value from each pair
    data_url[ar_val[0]] = ar_val[1];
  }

  return data_url;
}
CoursesWeb
  • 4,179
  • 3
  • 21
  • 27
0

I used satpal's answer to provide a nice Razor to JSON pipeline that works with Html.BeginForm, @Html.TextBoxFor etc.

The updated getUrlVars function looks like this:

function getUrlVars(url) {
    var hash;
    var myJson = {};
    var hashes = url.slice(url.indexOf('?') + 1).split('&');
    for (var i = 0; i < hashes.length; i++) {
        hash = hashes[i].split('=');
        var value = decodeURIComponent(hash[1]);
        value = value.replace("[\"", "");
        value = value.replace("\"]", "");
        value = value.replace(/\^.*/, "");
        myJson[hash[0]] = value;
    }
    return myJson;
}

The extra replace calls are for characters I get in my text boxes, probably via the dropdown magicSuggest lookups. The decodeURIComponent call cleans it up from %'s first.

I call it in a block like this:

    var serialized = $("#saveForm").serialize();
    var params = getUrlVars(serialized);

The Razor syntax I have looks like this:

@using (Html.BeginForm("SaveNewAddress", "Internal", FormMethod.Post, new { @Id = "saveForm" }))
{
    @Html.ValidationSummary()

    <table style="width: 100%; margin: 0 auto; padding: 10px">

        <tr>
            <td colspan="2">
                <label>Is this a Liliputian Address?</label>
            </td>
            <td colspan="4" style="font-size: 1.1em">

                <div style="float: left; margin-left: 10px">
                    <label class="label_check">
                        @Html.RadioButton("IsLiliputian", "Yes", true, new { @id = "IsLiliputianYes", @style = "width:30px" })
                    </label>
                    Yes
                </div>
                ...etc

This provides a nice way to get a bunch of data created in and via ASP.Net MVC controls in a js object that I can throw at a webservice via ajax.

Community
  • 1
  • 1
user326608
  • 2,210
  • 1
  • 26
  • 33
0

You might want to try something like

var url = require('url')
var your_json = url.parse( your_url, true );

I got this from here

ze miguel
  • 306
  • 3
  • 9
0
function getFormData(data){
    data = data.replace('%20', ' ');
    var jsonObj= {};

    var sep = data.split('&');
    for (var i = 0; i < sep.length; i++) {
        var getVals = sep[i].split('=');
        jsonObj[getVals[0]] = getVals[1];
    }
    return jsonObj;
}
Funner
  • 1