Skip to content

Instantly share code, notes, and snippets.

@arnogues
Last active October 24, 2018 16:05
Show Gist options
  • Save arnogues/c799c0b4da84eed751b3496464d0f3d0 to your computer and use it in GitHub Desktop.
Save arnogues/c799c0b4da84eed751b3496464d0f3d0 to your computer and use it in GitHub Desktop.
Simple url to json and json to url converter
function jsToUrl(js) {
return [""]
.concat(Object.keys(js))
.reduce((accumulator, key, i) => {
return `${accumulator}&${key}=${encodeURIComponent(js[key])}`;
})
.replace(/^&/, "?");
}
function urlToJs(url) {
return JSON.parse(
"{" +
url
.replace(/^\?/, "")
.split("&")
.map(item =>
item.replace(
/^(.+?)=(.*)$/,
(a, key, value) =>
`"${key}":"${decodeURIComponent(value).replace(/"/g, '\\"')}"`
)
)
.join(",") +
"}"
);
}
const json = {
foo: 12345677654,
bar: "buuuzzzzz",
foobar: true,
string: 'I am a "custom" string'
};
console.log(jsToUrl(json));
console.log(
urlToJs(
"?foo=12345677654&bar=buuuzzzzz&foobar=true&string=I%20am%20a%20%22custom%22%20string"
)
);
console.log(
urlToJs(
"foo=12345677654&bar=buuuzzzzz&foobar=true&string=I%20am%20a%20%22custom%22%20string"
)
);
console.log(
urlToJs(
"foo=12345677654&bar=buuuzzzzz&foobar=true&empty=&string=I%20am%20a%20%22custom%22%20string"
)
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment