Skip to content

pferreirafabricio/x-www-form-urlencoded-to-json

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

14 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

x-www-form-urlencoded to JSON

A simple web tool that converts an x-www-form-urlencoded string to JSON

license url



Note

Take a look at https://pferreirafabricio.github.io/x-www-form-urlencoded-to-json/ for a live test

⚙ How it works

The conversion is made in 6 simple steps:

x-wwww-form-urlencoded example: name=Tom&surname=Platz&age=68

  1. Blank characters at the start and at the end of the string are removed
  2. Split the string into an array by the & character
[
  'name=Tom',
  'surname=Platz',
  'age=68'
]
  1. Each string inside the array is split again, now by the = character
[
  ['name', 'Tom'],
  ['surname', 'Platz'],
  ['age', 68]
]
  1. 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

  1. 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
}
  1. 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
  );
}

✨ Features

  • 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

🏄‍♂️ Quick Start

  1. Clone this repository git clone https://github.com/pferreirafabricio/x-www-form-urlencoded-to-json.git
  2. Enter in the project's folder: cd x-www-form-urlencoded-to-json
  3. Open the index.html in your browser

🧱 This project was built with:

  • HTML
  • CSS
  • JavaScript

📚 References