0%

Hey! Do you have any query related to front end?

Sign in Sign up

Convert query string to jsonBack

Query string in DOM has always been a big problem. Searched a lot but could not found any suitable solution for this. Normally people convert it into keys and pairs format. But in latest browser found that, this can be done by using JSON Object, which is available in modern browser.

Getting started:

First you will have to follow older fashion, that is to convert the query string in to an array by replacing "?" from the string, through slice() function.

location.search.slice(1);

Then you will have to split the Array by passing it the ‘&’ character.

var pairs = location.search.slice(1).split('&');

Now using the array .forEach() function we can go through pairs and split them again, this time we will use "=". By this way we will get index "0" as key and index "1" as value.

And by using decodeURIComponent function we will remove any HTML encoding.

var pairs = location.search.slice(1).split('&');

var result = {};
pairs.forEach(function(pair) {
    pair = pair.split('=');
    result[pair[0]] = decodeURIComponent(pair[1] || '');
});

Last step:

The final step is to use JSON.stringify method to parse the object, and then again call the JSON.parse() function to convert that back to an object.

Final code goes like this:

function QueryToJSON() {            
    var pairs = location.search.slice(1).split('&');
    
    var result = {};
    pairs.forEach(function(pair) {
        pair = pair.split('=');
        result[pair[0]] = decodeURIComponent(pair[1] || '');
    });

    return JSON.parse(JSON.stringify(result));
}

var query_string = QueryToJSON();

How to comment:

  • Create an account in discuss by clicking on login next to arrow.
  • Create password for discuss and varify your email id, through your mail.
  • Refresh page and comment.

You might also like

  • Convert query string to json

    Convert querystring to json

    • 210
    • 0
    • 210
    • facebook icon
    • twitter icon
    • google plus
  • Centralize your content

    Position your content according to your choice

    • 248
    • 5
    • 248
    • facebook icon
    • twitter icon
    • google plus
  • Javascript smart tooltip

    Make your title tag as tooltip.

    • 288
    • 15
    • 288
    • facebook icon
    • twitter icon
    • google plus

Latest quries posted

gopa kumarabout 3 years ago

amit singhabout 3 years ago

rahmat aliabout 3 years ago

mandavi tiwariabout 3 years ago

rahul sharmaabout 3 years ago

Ask question
Latest video
Learn Angular
Profile pic
Guest Back
Username
Password