Encodes and decodes JavaScript objects into/from an URL usable string
✨Demo
The goal was to create URLs as small as possible by using a template approach. If don't care about the length of the url, you can just use something simpler like this:
const serialize = obj => encodeURIComponent(JSON.stringify(obj));
const deserialize = str => JSON.parse(decodeURIComponent(str));
Otherwise, read on.
npm i json2url
<script src="https://unpkg.com/json2url/dist/index.umd.js"></script>
Download https://unpkg.com/json2url/dist/index.umd.js and link it in your html.
<input type="range" id="a" value="0" />
<input type="range" id="b" value="0" />
<input type="range" id="c" value="0" />
<input type="range" id="d" value="0" />
<button onclick="serialize()">Serialize</button>
<textarea id="out" cols="30" rows="10"></textarea>
<script src="https://unpkg.com/json2url/dist/index.umd.js"></script>
<script>
const template = {
a: 0,
b: 0,
c: 0,
d: 0,
};
const config = { ...template };
const inputIds = ['a', 'b', 'c', 'd'];
window.addEventListener('load', () => {
inputIds.forEach((id) => {
document.getElementById(id).addEventListener('change', (e) => {
config[id] = e.target.value;
});
});
});
function serialize() {
const serialized = json2Url.serialize(config);
document.getElementById('out').value = serialized;
console.log(json2Url.deserialize(serialized, template));
}
</script>
npm run test
This project is licensed under the MIT License - see the LICENSE file for details.