0

I have a URL query that looks like this:

view-mode=grid&filters%5Bone%5D%3D1%26filters%5Btwo%5D%3D2

Ultimately I want to be able to parse the parameters in both PHP and Javascripting (using jQuery). No issues parsing in PHP using $_GET. Trying to figure out how to do it using Javascript. The final object in Javascript should look like this:

{ "view-mode" : "grid", "filters" : { "one" : "1", "two" : "2" } }

Any suggestions? I am using URI.js for some building and parsing already.

Thanks

Ward
  • 3,318
  • 3
  • 30
  • 50
  • 2
    Possible duplicate of [Convert URL parameters to a javascript object](http://stackoverflow.com/questions/8648892/convert-url-parameters-to-a-javascript-object) – Ohgodwhy Apr 04 '16 at 18:54
  • I've tried that solution, but the result is `{filters[one]: "1", filters[two]: "2"}` – Ward Apr 04 '16 at 19:08
  • Where is this data coming from? Are you generating it yourself? Can you json encode the object and pass it, instead of however it is being passed now? – Alden Be Apr 04 '16 at 19:21
  • It's coming from a URL. I think I figured it out. Testing now... Looks like I can use the BBQ plugin to deparam the querystring. http://benalman.com/code/projects/jquery-bbq/docs/files/jquery-ba-bbq-js.html#jQuery.deparam.querystring – Ward Apr 04 '16 at 19:26

1 Answers1

0

Figured it out:

I used URL.js to get the query parameters using URI(location.href).query(true)

I get an object with a few properties, including "view-mode" and "filters[one]=1&filters[two]=2" where "filters[one]=1&filters[two]=2" is an object (based on the way URL.js parses the query).

Then I iterate through the object and check if the property is an object. If it is, I use Ben Alman's BBQ jQuery Plugin to parse the property name which turns:

filters%5Bone%5D%3D1%26filters%5Btwo%5D%3D2

into:

{ "filters" : { "one" : "1", "two" : "2" } }

The URI.js parsing method also results in a few properties that have no value such as "*filters[one]=1&filters[two]=21*" and "*filters[one]=1&filters[two]=2[]*". I ignore those.

Then I can combine the original properties that aren't objects such as "view-mode=grid" with the parsed properties that are objects, such as "filters%5Bone%5D%3D1%26filters%5Btwo%5D%3D2" and I end up with:

{ "view-mode" : "grid", "filters" : { "one" : "1", "two" : "2" } }

End result is that both Javascript and PHP can read and understand the query parameters.

Ward
  • 3,318
  • 3
  • 30
  • 50