How to Create Query Parameters in JavaScript ?
The task is to create a query URL for GET request given a JSON object using javaScript. GET query parameters in an URL are just a string of key-value pairs connected with the symbol &. To convert a JSON object into a GET query parameter we can use the following approach.
- Make a variable query.
- Loop through all the keys and values of the json and attach them together with ‘&’ symbol.
Examples:
Input: {'website':'geeks', 'location':'india'} Output: website=geeks&location=india
Syntax:
function encodeQuery(data){ let query = "" for (let d in data) query += encodeURIComponent(d) + '=' + encodeURIComponent(data[d]) + '&' return query.slice(0, -1) }
Below examples implements the above approach:
Example 1:
<script> function encodeQuery(data){ let query = "" for (let d in data) query += encodeURIComponent(d) + '=' + encodeURIComponent(data[d]) + '&' return query.slice(0, -1) } // Json object that should be // converted to query parameter data = { 'website' : 'geeks' , 'location' : 'india' } queryParam = encodeQuery(data) console.log(queryParam) </script> |
Output:
website=geeks&location=india
Example 2: In this example, we will create a complete URL from the given JSON data.
<script> function encodeQuery(data){ let query = data.url for (let d in data.params) query += encodeURIComponent(d) + '=' + encodeURIComponent(data.params[d]) + '&' ; return query.slice(0, -1) } // Json object that should be // converted to query parameter data = { url : 'www.geeksforgeeks.com/' , params : { 'website' : 'geeks' , 'location' : 'india' } } queryParam = encodeQuery(data) console.log(queryParam) </script> |
Output:
www.geeksforgeeks.com/website=geeks&location=india
Please Login to comment...