Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any native function to convert json to url parameters?

I need convert json object to url form like: "parameter=12&asd=1"

I done with this:

        var data = {             'action':'actualiza_resultado',             'postID': 1,             'gl': 2,             'gl2' : 3         };          var string_=JSON.stringify(data);          string_=string_.replace(/{/g, "");         string_=string_.replace(/}/g, "");         string_=string_.replace(/:/g, "=")         string_=string_.replace(/,/g, "&");         string_=string_.replace(/"/g, ""); 

But i wonder if there any function in javascript or in JSON object to do this?

like image 511
fpilee Avatar asked Jan 25 '13 15:01

fpilee


People also ask

Can you put JSON in URL?

JSON→URL text is limited to a subset of the characters allowed in a URL query string. All other characers must be percent encoded. The [ , ] , { , and } characters are not allowed in a URL query string so objects and arrays both begin with ( and end with ) .

How can I get JSON data from URL?

Get JSON From URL Using jQuery Usually, jQuery. getJSON(url, data, success) is the signature method for getting JSON from an URL. In this case, the URL is a string that ensures the exact location of data, and data is just an object sent to the server.

Can you use JavaScript to get URL parameter values?

The short answer is yes Javascript can parse URL parameter values. You can do this by leveraging URL Parameters to: Pass values from one page to another using the Javascript Get Method. Pass custom values to Google Analytics using the Google Tag Manager URL Variable which works the same as using a Javascript function.


2 Answers

jQuery provides param that does exactly that. If you don't use jquery, take at look at the source.

Basically, it goes like this:

url = Object.keys(data).map(function(k) {     return encodeURIComponent(k) + '=' + encodeURIComponent(data[k]) }).join('&') 

2019 update: there's now a built-in object URLSearchParams for this type of thing:

let myParams = {'foo': 'hi there', 'bar': '???'};    let u = new URLSearchParams(myParams).toString();    console.log(u);
like image 166
georg Avatar answered Sep 20 '22 17:09

georg


Using ES6 syntax:

var data = {    'action':'actualiza_resultado',    'postID': 1,    'gl': 2,    'gl2' : 3  };    let urlParameters = Object.entries(data).map(e => e.join('=')).join('&');    console.log(urlParameters);
like image 27
Tareq Avatar answered Sep 18 '22 17:09

Tareq