Last active
September 20, 2021 20:48
-
-
Save TanmayChakrabarty/5546637bd29071c2c7ddf8c8cefb5a43 to your computer and use it in GitHub Desktop.
build URL query part from a given JSON object
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 buildUrlQueryFromJson(data, opening_array, encode){ | |
let output = []; | |
if(typeof encode === 'undefined') encode = false; | |
if(typeof opening_array !== 'string') opening_array = ''; | |
let next_opening_array = ''; | |
if((typeof data === 'object' || Array.isArray(data)) && data !== null){ | |
for(var i in data){ | |
if(opening_array.length) | |
next_opening_array = opening_array+'['+encodeURIComponent(i)+']'; | |
else | |
next_opening_array = i; | |
if((typeof data[i] === 'object' || Array.isArray(data[i])) && data[i] !== null){ | |
output.push(buildUrlQueryFromJson(data[i], next_opening_array)); | |
} | |
else if(data[i] !== null){ | |
if(opening_array.length) | |
output.push(opening_array+'['+i+']'+'='+encodeURIComponent(data[i])); | |
else | |
output.push(i+'='+encodeURIComponent(data[i])); | |
} | |
} | |
} | |
return encode ? encodeURI(output.join('&')) : output.join('&'); | |
} |
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 testJson = { | |
order: { | |
0: { | |
column: 1 | |
} | |
}, | |
a: 'b', | |
c: 10 | |
}; | |
console.log(buildUrlQueryFromJson(testJson, '')); | |
console.log(buildUrlQueryFromJson(testJson, '', true)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment