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':'neveropen', 'location':'india'}
Output: website=neveropen&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':'neveropen', Â Â Â Â 'location':'india'} queryParam = encodeQuery(data) console.log(queryParam) </script> |
Output:
website=neveropen&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.neveropen.com/',     params : {         'website':'neveropen',         'location':'india'    } } queryParam = encodeQuery(data) console.log(queryParam) </script> |
Output:
www.neveropen.com/website=neveropen&location=india
