A simple web tool that converts an x-www-form-urlencoded string to JSON
Note
Take a look at https://pferreirafabricio.github.io/x-www-form-urlencoded-to-json/ for a live test
The conversion is made in 6 simple steps:
x-wwww-form-urlencoded example:
name=Tom&surname=Platz&age=68
- Blank characters at the start and at the end of the string are removed
- Split the string into an array by the
&
character
[
'name=Tom',
'surname=Platz',
'age=68'
]
- Each string inside the array is split again, now by the
=
character
[
['name', 'Tom'],
['surname', 'Platz'],
['age', 68]
]
- Each array inside the array maps the values to the function decodeURIComponent
['name', 'Tom'] -> [decodeURIComponent('name'), decodeURIComponent('Tom')]
['surname', 'Platz'] -> [decodeURIComponent('surname'), decodeURIComponent('Platz')]
['age', '68'] -> [decodeURIComponent('age'), decodeURIComponent('68')]
We need to do this because some values may be encoded, for example:
From=%2B12012537162
where%2B
, when decoded by decodeURIComponent, will return the+
character
- We take the array of array, now adequately sanitized, and call the Object.fromEntries, to transform the array of arrays into an Object
{
name: 'Tom',
surname: 'Platz',
age: 68
}
- Finally we call JSON.stringify using the third parameter (space) as
2
to have better visualization of the JSON
{
"name": "Tom",
"surname": "Platz",
"age": "68"
}
The final function will be:
function convertToJson(value) {
return JSON.stringify(
Object.fromEntries(
value
.trim()
.split("&")
.map((s) => s.split("="))
.map((pair) => pair.map(decodeURIComponent))
),
undefined,
2
);
}
- Converts an x-www-form-urlencoded string to JSON
- Provides a user-friendly interface to input the string and view the converted JSON
- Allows users to copy the converted JSON to the clipboard
- Free and online tool
- Clone this repository
git clone https://github.com/pferreirafabricio/x-www-form-urlencoded-to-json.git
- Enter in the project's folder:
cd x-www-form-urlencoded-to-json
- Open the
index.html
in your browser
- HTML
- CSS
- JavaScript