Last active
December 10, 2021 19:35
-
-
Save westonganger/1f737e601614a875d23912ceebfedea1 to your computer and use it in GitHub Desktop.
Javascript JSON to Params Query String Generator
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
| window.generate_params_query_string = function(json){ | |
| if(typeof json == 'string'){ | |
| json = JSON.parse(json); | |
| } | |
| var params_str_array = []; | |
| var parse_plain_value = function(current_obj, current_prefix){ | |
| var strParam = current_prefix + "=" + encodeURIComponent(current_obj); | |
| params_str_array.push(strParam); | |
| }; | |
| var parse_array = function(current_obj, current_prefix){ | |
| current_obj.forEach(function(val){ | |
| if(Array.isArray(val)){ | |
| parse_array(val, current_prefix); | |
| }else if(typeof val === 'object' && val !== null){ | |
| parse_object(val, current_prefix); | |
| }else{ | |
| parse_plain_value(val, current_prefix) | |
| } | |
| }); | |
| }; | |
| var parse_object = function(current_obj, current_prefix){ | |
| Object.keys(current_obj).forEach(function(key, i){ | |
| var val = current_obj[key]; | |
| if(Array.isArray(val)){ | |
| if(current_prefix){ | |
| var prefix = current_prefix+"["+key+"][]"; | |
| }else{ | |
| var prefix = key+"[]"; | |
| } | |
| parse_array(val, prefix); | |
| }else if(typeof val === 'object' && val !== null){ | |
| if(current_prefix){ | |
| var prefix = current_prefix+"["+key+"]"; | |
| }else{ | |
| var prefix = key; | |
| } | |
| parse_object(val, prefix); | |
| }else{ | |
| if(current_prefix){ | |
| var prefix = current_prefix+"["+key+"]"; | |
| }else{ | |
| var prefix = key; | |
| } | |
| parse_plain_value(val, prefix) | |
| } | |
| }); | |
| }; | |
| parse_object(json, null); | |
| var params_str = params_str_array.join("&") | |
| return params_str; | |
| }; |
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
| // Using JSON String | |
| window.generate_params_query_string(json_str); | |
| // Using an object or parsed JSON | |
| window.generate_params_query_string(obj); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment