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:



filter_none

edit
close

play_arrow

link
brightness_4
code

<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>

chevron_right


Output:

website=geeks&location=india

Example 2: In this example, we will create a complete URL from the given JSON data.

filter_none

edit
close

play_arrow

link
brightness_4
code

<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>

chevron_right


Output:

www.geeksforgeeks.com/website=geeks&location=india

full-stack-img




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.