I've seen a few answers that provide workarounds or alternatives, but I'm hoping for something either really slick and indirect or the proper functions to go from JSON object/array to a standard multipart/form-data style query string, most ideal matching what PHP function http_build_query
would return for a JSON object that's been encoded to local array/object.
Basic premise:
When sending API calls over POST/PUT, the message body is typically JSON-encoded, similar to:
{
"filter": [
{
"field_x": {
"$gte": "9"
}
},
{
"assigned_user_link.user_name": "user7"
},
{
"date_entered": {
"$gte": "2014-08-01"
}
}
]
}
And that's totally awesome and works. Sending the same above parameters on a GET request should look like:
?filter[0][field_x][$gte]=9&filter[1][assigned_user_link.user_name]=user7&filter[2][date_entered][$gte]=2014-08-01
Both are exactly right for their context, instead of passing URL-encoded version of JSON used previously.
In PHP, I can take a few steps to swap between the two :
parse_str($_SERVER['QUERY_STRING'],$filter_array);
$filter_json = json_encode($filter_array); // Now I've got the JSON
$filter_phobj = json_decode($filter_json); // Now I've got the native Object/Array
$filter_query = rawurldecode(http_build_query($filter_phobj)); // And full circle
What I'm looking for is an elegant or straightforward or pre-existing standard approach within Javascript / DOM API that will accept the JSON above and return the query string.
Most importantly is the handling of objects with property as array, which would get handled in query string as :
key[0][subkey1][subval1]&key[1][subkey2][subval2]
I'm certain this is a trivial task, but all search results lean toward inelegant looping (which could be replaced with better looping, not voting loops down) or side-step the issue and insist that "sending as url-encoded json is better anyway. here's how you do that." URL-encoded-json is a different way, and if both sides of the request/response are up to it, it works. But the goal here is a JS function/library that can send API calls using the same JSON object but appropriately reworked for the context.