Skip to content


Subversion checkout URL

You can clone with
Download ZIP


JSON Serializer on datasets gives unexpected results. #549

bryanrite opened this Issue · 2 comments

2 participants


I have been using the json_serializer plugin for generating JSON for an API. Everything works great on single instances:

1.9.3p194 :001 > Relationship.first
 => #<Relationship @values={:id=>5, :on_air=>true, :created_at=>2012-09-13 12:47:12 -0700, :updated_at=>nil}> 
1.9.3p194 :002 > Relationship.first.to_json(naked: true, only: :id)
 => "{\"id\":5}"

When I want to convert a collection of Relationship objects, I get some unexpected results:

1.9.3p194 :004 > Relationship.all.to_json(naked: true, only: :id)
 => "[{\"id\":5,\"on_air\":true,\"created_at\":\"2012-09-13T12:47:12-07:00\",\"updated_at\":null},{\"id\":6,\"on_air\":true,\"created_at\":\"2012-09-13T12:47:55-07:00\",\"updated_at\":null},{\"id\":7,\"on_air\":true,\"created_at\":\"2012-09-13T12:48:29-07:00\",\"updated_at\":null}]" 

It generates proper JSON, but does not take options into account. I understand this is running to_json on an instance of Array.

Using filters as the documentation shows:

1.9.3p194 :005 > Relationship.filter().to_json(naked: true, only: :id)
 => "[{\"json\":\"{\\\"id\\\":5}\"},{\"json\":\"{\\\"id\\\":6}\"},{\"json\":\"{\\\"id\\\":7}\"}]" 

Produces a better dataset but not valid JSON. Looks like its been encoded twice.

Using the array: option produces the same as above:

1.9.3p194 :021 > Relationship.to_json(array: Relationship.filter(), naked: true, only: :id)
 => "[{\"json\":\"{\\\"id\\\":5}\"},{\"json\":\"{\\\"id\\\":6}\"},{\"json\":\"{\\\"id\\\":7}\"}]"

What I would expect is something more like:


Is this the intended behaviour?


ruby's json library defines Array#to_json such that it does not pass arguments given to it to members of the array, which is why Model.all.to_json will not respect an options hash if you pass one. That is expected.

The other results with the double encoding are because you are using 'active_support/json', which breaks Sequel's json_serializer plugin because it changes the to_json API. Basically active_support/json makes incompatible changes to ruby's json library. I consider this a bug in ActiveSupport.

This question has come up before, I'll add a note to the plugin documentation to be explicit that the problem is with ActiveSupport.


Thanks Jeremy. I was using Carrierwave which requires activesupport and I didn't realize this was happening. Thanks for your tips on undoing this as well.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.