Karolis Karolis - 1 year ago 101
JSON Question

Rails converts empty arrays into nils in params of the request

I have a Backbone model in my app which is not a typical flat object, it's a large nested object and we store the nested parts in TEXT columns in a MySQL database.

I wanted to handle the JSON encoding/decoding in Rails API so that from outside it looks like you can POST/GET this one large nested JSON object even if parts of it are stored as stringified JSON text.

However, I ran into an issue where Rails magically converts empty arrays to

values. For example, if I POST this:

name: "foo",
surname: "bar",
nested_json: {
complicated: []

My Rails controller sees this:

:name => "foo",
:surname => "bar",
:nested_json => {
:complicated => nil

And so my JSON data has been altered..

Has anyone run into this issue before? Why would Rails be modifying my POST data?


Here is where they do it:


And here is ~why they do it:


So now the question is, how to best deal with this in my nested JSON API situation?

Answer Source

After much searching, I discovered that you starting in Rails 4.1 you can skip the deep_munge "feature" completely using

config.action_dispatch.perform_deep_munge = false

I could not find any documentation, but you can view the introduction of this option here: https://github.com/rails/rails/commit/e8572cf2f94872d81e7145da31d55c6e1b074247

There is a possible security risk in doing so, documented here: https://groups.google.com/forum/#!topic/rubyonrails-security/t1WFuuQyavI

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download