Speed up JSON generation with oj

Updated . Posted . Visible to the public.

Using this gem I could get JSON generation from a large, nested Ruby hash down from 200ms to 2ms.

Its behavior differs from the default JSON.dump or to_json behavior in that it serializes Ruby symbols as ":symbol", and that it doesn't like an ActiveSupport::HasWithIndifferentAccess.

There are also some issues Show archive.org snapshot if you are on Rails < 4.1 and want it to replace #to_json (but you can always just call Oj.dump explicitely).

Security warning: Oj does not escape HTML entities in JSON

Be aware that Oj.dump is not aware of ActiveSupport's escape_html_entities_in_json setting Show archive.org snapshot . You need to escape its output to prevent XSS vulnerabilities.
You might be able to fix this by hooking Oj into to_json but there are some issues Show archive.org snapshot and I haven't tried it. Please update this card if you find out.

What I did test successfully was the workaround below.

Workaround

In Rails 4 you can wrap the output of Oj.dump(...) in an escape_json tag to escape HTML entities in Strings:

<script>
  myFunction(<%= escape_json OJ.dump(@data) %>)
</script>

Earlier Rails versions have an unusable implementation of escape_json Show archive.org snapshot (it deletes all your quotes!), so you need to load the attached file that backports the Rails 4 implementation like so:

<script>
  myFunction(<%= Rails4JsonEscape.escape_json OJ.dump(@data) %>)
</script>
Profile picture of Henning Koch
Henning Koch
Last edit
Henning Koch
License
Source code in this card is licensed under the MIT License.
Posted by Henning Koch to makandra dev (2014-11-16 16:44)