Add a JSON to a URL

Let's assume that you have the following object:

javascript
let json = {
    name: 'Erik Martín',
    city: 'Bangkok',
    age: 31
}

Let's assume that you want to add that object at the end of a URL:

javascript
let url = `https://erikmartinjordan.com/${json}`

If you print the result:

javascript
console.log(url) // 'https://erikmartinjordan.com/[object Object]'

You need to transform the JSON into a string:

javascript
let url = `https://erikmartinjordan.com/${JSON.stringify(json)}`

But if you print the result:

javascript
console.log(url) // 'https://erikmartinjordan.com/{"name":"Erik Martín","city":"Bangkok","age":31}'

The URL has spaces and special characters. To prevent it, encode the URL:

javascript
let url = `https://erikmartinjordan.com/${encodeURIComponent(JSON.stringify(json))}`

Finally:

javascript
console.log(url) // 'https://erikmartinjordan.com/%7B%22name%22%3A%22Erik%20Mart%C3%ADn%22%2C%22city%22%3A%22Bangkok%22%2C%22age%22%3A31%7D'

Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.