Convert URL to json

2020-02-03 16:20发布

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

6条回答
贪生不怕死
2楼-- · 2020-02-03 16:48

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"}
查看更多
成全新的幸福
3楼-- · 2020-02-03 16:57

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;
}
查看更多
做个烂人
4楼-- · 2020-02-03 17:06

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.

查看更多
乱世女痞
5楼-- · 2020-02-03 17:08

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/

查看更多
劫难
6楼-- · 2020-02-03 17:10

You might want to try something like

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

I got this from here

查看更多
对你真心纯属浪费
7楼-- · 2020-02-03 17:11

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. :)

查看更多
登录 后发表回答