Last active
April 22, 2022 13:04
-
-
Save btaillon-coveo/02495eec3535a007704779284ff2d08a to your computer and use it in GitHub Desktop.
Chrome raw request payload decoder
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<meta http-equiv="X-UA-Compatible" content="IE=edge"> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
<title>Recursive decoder</title> | |
<script> | |
/** | |
* @param {string} obj | |
* @returns {string} | |
*/ | |
function tryParseJSON(obj) { | |
try { | |
const parsedValue = JSON.parse(obj); | |
if (typeof parsedValue !== 'object') { | |
return parsedValue; | |
} | |
if (Array.isArray(parsedValue)) { | |
return parsedValue.map(value => tryParseJSON(value)); | |
} | |
return Object.fromEntries( | |
Object.entries(parsedValue).map(([key, value]) => [key, tryParseJSON(value)]) | |
); | |
} catch (e) { | |
return obj; | |
} | |
} | |
document.addEventListener('DOMContentLoaded', () => { | |
/** @type {HTMLButtonElement} */ | |
const convertBtn = document.getElementById('convert-btn'); | |
/** @type {HTMLSelectElement} */ | |
const sourceTypeSelect = document.getElementById('source-type'); | |
/** @type {HTMLTextAreaElement} */ | |
const sourceEl = document.getElementById('source'); | |
/** @type {HTMLTextAreaElement} */ | |
const outputEl = document.getElementById('output'); | |
convertBtn.addEventListener('click', () => { | |
switch (sourceTypeSelect.value) { | |
case 'uri': | |
const components = sourceEl.value.split('&').map((component) => { | |
const [key, value] = component.split('='); | |
const parsedValue = tryParseJSON(decodeURIComponent(value)); | |
return [key, parsedValue]; | |
}); | |
const finalObj = Object.fromEntries(components); | |
outputEl.value = JSON.stringify(finalObj); | |
break; | |
case 'json': | |
outputEl.value = JSON.stringify(tryParseJSON(sourceEl.value)); | |
break; | |
} | |
}); | |
}); | |
</script> | |
</head> | |
<body> | |
<textarea id="source" cols="30" rows="10"></textarea> | |
<select id="source-type"> | |
<option value="uri">URI</option> | |
<option value="json">JSON</option> | |
</select> | |
<button id="convert-btn">Convert</button> | |
<textarea id="output" cols="30" rows="10"></textarea> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment