Created
September 20, 2021 20:42
-
-
Save TanmayChakrabarty/15188b52a09543c7263f3ee1a600bc86 to your computer and use it in GitHub Desktop.
Build a JSON from given query part of an URL
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 buildJsonFromUrlQuery(query){ | |
if(!query || typeof query !== 'string' || !query.length) return {}; | |
var partsArray = query.split('&'); | |
var partsObject = {}; | |
for(let i in partsArray){ | |
let thisPart = partsArray[i]; | |
let keyValue = thisPart.split('='); | |
let key = decodeURI(keyValue[0]); | |
let value = keyValue[1]; | |
if(key.includes('[')){ | |
let keyJsonString = '{"' + key.replaceAll(/\]\[/ig, '":{"').replaceAll(/\[/ig, '":{"').replaceAll(/\]/ig, '":') + '"' + value + '"' + ''.padEnd((key.match(/\]/g) || []).length, '}') + '}'; | |
let keyJsonObject = JSON.parse(keyJsonString); | |
$.extend(true, partsObject, keyJsonObject); | |
} | |
else{ | |
partsObject[key] = value; | |
} | |
} | |
return partsObject; | |
} |
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
let textQuery = 'action=view&month_year=2021-09&fk_district_id=&fk_subdistrict_id=&fk_union_id=null&order%5B0%5D%5Bcolumn%5D=1&order%5B0%5D%5Bdir%5D=asc'; | |
console.log(buildJsonFromUrlQuery(textQuery)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment