Last active
October 24, 2018 16:05
-
-
Save jmcorpdev/c799c0b4da84eed751b3496464d0f3d0 to your computer and use it in GitHub Desktop.
Simple url to json and json to url converter
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
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