1

Rails allows the generation of query strings by passing a hash to a url_for type helper:

root_path({ :animals => {:dogs => ['pluto','spot'], :cats => 'garfield'} })

This will generate a url like:

http://example.com/?animals[dogs][]=pluto&animals[dogs][]=spot&animals[cats]=garfield

I want to use javascript to turn this into a JSON object so I have an object that matches the hash passed into the url helper in rails.

Using prototype.js I can call:

var params = window.location.search.toQueryParams();

params is a object but the original nested structure is not retained, instead I get:

{
  "animals[dogs][]" : ["pluto","spot"],
  "animals[cats]" : "garfield"
}

What I really want is:

{
  "animals" : {
    "dogs" : ["pluto","spot"],
    "cats" : "garfield"
  }
}

Also the reverse would be useful too. Prototype.js has toQueryString which in this case just returns an empty string:

Object.toQueryString({
  "animals" : {
    "dogs" : ["pluto","spot"],
    "cats" : "garfield"
  }
});

Is there a library of method that provides for this?

2

1 Answer 1

1

To answer my own question:

I found Ben Alman's jQuery BBQ which does it with a jQuery plugin.

http://benalman.com/code/projects/jquery-bbq/examples/deparam/?animals[dogs][]=pluto&animals[dogs][]=spot&animals[cats]=garfield

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.