1

I was wondering if it is possible to get the url parameter as JSON object using window object.

For ex. I have the url "/#/health?firstName=tom&secondName=Mike"

and get the value as {"firstName": "tom", "secondName": "Mike"}

I tried to explore the window object but could not find any help.

I think I can try parsing the string firstName=tom&secondName=Mike and convert this to json but this doesn't look like a great approach. BTW if there are smart way to parse, that too will be appreciated.

Please let me know if I should provide any more information.

kaounKaoun
  • 601
  • 1
  • 9
  • 21

3 Answers3

2

In Angular you can get the URL with:

this.router.url

Once you've got the URL, you should use the very popular (14 mill downloads a week) npm qs module:

var qs = require('qs');
var obj = qs.parse('firstName=tom&secondName=Mike');

returns:

{
  firstName: 'tom'
  secondName: 'mike'
}
danday74
  • 52,471
  • 49
  • 232
  • 283
2

Using straight javascript first get the params and then convert them into an object:

<script type="text/javascript">

    // params will be an object with key value pairs based on the url query string
    var params = paramsToObject();
    console.log(params);

    // Get the parameters by splitting the url at the ?
    function getParams() {
        var uri = window.location.toString();
        if (uri.indexOf("?") > 0) {
            var params = uri.substring(uri.indexOf("?") + 1, uri.length);
            return params;
        }
        return "";
    }

    // Split the string by & and then split each pair by = then return the object
    function paramsToObject() {
        var params = getParams().split("&");
        var obj = {};

        for (p in params) {
            var arr = params[p].split("=");
            obj[arr[0]] = arr[1];
        }

        return obj;
    }
</script>

If using Angular: You can use the qs npm module suggested in the answer by danday74.

1
const str = 'abc=foo&def=%5Bbar%5D&xyz=5'

    // reduce takes an array and reduces it into a single value
    const nameVal = str.split('&').reduce((prev, curr) => {
    // see output here in console for clarity:
    console.log('curr= ', curr, ' prev = ', prev)
    prev[decodeURIComponent(curr.split('=')[0])] = decodeURIComponent(curr.split('=')[1]);
    return prev;
}, {});

// invoke 
console.log(nameVal);
ObjectMatrix
  • 325
  • 1
  • 3
  • 9