can anyone tell me if there is a way to use json object key values in url? Like when we use a open api like openweathermap we give its url some parameters like city name ect ,and they send relative data to that value, I want to know how they do it.
Asked
Active
Viewed 346 times
0
-
Do you have any specific example of what you are trying to achieve? – Ranga Apr 30 '22 at 03:56
-
Does this answer your question? [Serialize object to query string in JavaScript/jQuery](https://stackoverflow.com/questions/3308846/serialize-object-to-query-string-in-javascript-jquery) – Salvino D'sa Apr 30 '22 at 04:07
-
to Ranga Dewasinghe .. i am trying to make a shopping website where my all products data are stored in a json file like this fashion={ productone={name,ect,category},producttwo{name,ect category} } they all have same key called category with different values like men, kids, ect . i want to pass object key category in fetch api url so whenever i change its value through useState i can fetch same category products in my application , but i don't know how to pass a object key in url – Vishal Solanki Apr 30 '22 at 07:22
-
to salvino : sory this won't work for me – Vishal Solanki Apr 30 '22 at 07:35
-
you can use `post` request, try googling `post with fetch` – Jimmy Apr 30 '22 at 20:59
1 Answers
0
I think this is what you're looking for:
function jsonToQueryString(json) {
return '?' +
Object.keys(json).map(function(key) {
return encodeURIComponent(key) + '=' + encodeURIComponent(json[key]);
}).join('&');
}
const baseUrl = 'http://example.com';
const params = {
lat: 'x',
long: 'y',
limit: 50
};
console.log(`${baseUrl}${jsonToQueryString(params)}`)

Salvino D'sa
- 4,018
- 1
- 7
- 19