to_json
to_json copied to clipboard
Serializer streaming in Rails
Hi,
The README talks about this library's ability to stream the JSON generation. Is there a way to take advantage of this in my Rails 4 controllers, and stream the response JSON straight from the serializer? Currently what happens is I call json! and render the resulting JSON string...but that can be very large, and it might be beneficial to take advantage of Rails 4's ActionController::Live abilities.
What do you think?
Here's an example of ActionController::Live: http://www.sitepoint.com/streaming-with-rails-4/
Yes that's the kind of thing I want to_json to support, streaming large results was a primary consideration in the design. When I first wrote to_json the stream support wasn't in Oj but now its there it should be possible to wire it up to the controllers response.stream
I plan to do a bit of work on to_json this coming week to add as an official gem so I will also look at adding the streaming suport if you would be happy to try it with rails in your app/environment.
@ahacking I would be glad to try it out in my app for sure.
Oj::StreamWriter takes an IO object as an argument when you initialize it, so I thought perhaps it would just be a matter of passing the response.stream object to it in #encode! and the writer would write to the stream as the JSON is pushed. It didn't work, unfortunately, but it was worth a try ;)
That's very much how it will work, I need to add support for setting up Oj with a stream in the to_json initializers. Currently it just initializes an Oj context using a string buffer serializer.
It will be a very simple addition and I'll get onto it once I'm back at my office as I'm away having a break from work currently.
Sounds great. Have a good break :-)