Skip to content

Instantly share code, notes, and snippets.

@wlib
Last active December 15, 2016 02:40
Show Gist options
  • Save wlib/b4d193490d21330c417acea10aaeb5c1 to your computer and use it in GitHub Desktop.
Save wlib/b4d193490d21330c417acea10aaeb5c1 to your computer and use it in GitHub Desktop.
Parse a URL query i.e. https://example.com/page?queryKey=value&embeddedJson={"json":{"can":"be%20embedded","nested":true}} into an object using javascript. Parses both key=value pairs and nested JSON just fine.
// Without an argument, just parse the current page's URL, if an argument is supplied, parse that
function parseQuery(query = window.location.search.substring(1)) {
// Decode the URL-safe query string into a regular string e.g.("%20" => " ")
const decodedQuery = decodeURIComponent(query);
// Split that string at every "&" to get all the key=value pairs
const allpairs = decodedQuery.split("&");
// Declare an object to hold our output
const out = {};
// This regex matches what seems to look like valid JSON
const regex = /^[\[|\{](\s|.*|\w)*[\]|\}]$/g;
for (let i = 0; i < allpairs.length; i++) {
// Split our key=value pairs
let pair = allpairs[i].split("=");
let key = pair[0];
let val = pair[1];
// If the value of this pair is matched and determined to be JSON, attempt to parse it
if (val.match(regex)) {
// If it is valid JSON then parse it and add it
try {
out[key] = JSON.parse(val);
}
// If it isn't valid then warn about it and add it as a regular string
catch (error) {
console.warn("matched what appeared to be json, failed to parse it");
out[key] = val;
}
}
// If the value is just a normal, non-json value, add it normally
else {
out[key] = val;
}
}
// Return the final output
return out;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment