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)
}
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)
}
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
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!
Looking for a place to share your ideas, learn, and connect? Our Community portal is just the spot! Come join us and see what all the buzz is about!
Last Updated :
18 Mar, 2020
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...