Read more

Speed up JSON generation with oj

Henning Koch
November 16, 2014Software engineer at makandra GmbH

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

Illustration web development

Do you need DevOps-experts?

Your development team has a full backlog? No time for infrastructure architecture? Our DevOps team is ready to support you!

  • We build reliable cloud solutions with Infrastructure as code
  • We are experts in security, Linux and databases
  • We support your dev team to perform
Read more Show archive.org snapshot

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>
Posted by Henning Koch to makandra dev (2014-11-16 17:44)