ilovebigmacs ilovebigmacs - 1 year ago 59
JSON Question

Why is Rails to_json giving a different result than Ruby to_json?

I have a Ruby script that converts a hash to json and writes it into a file. I use the


In the file, I get the following result:


I copied this script in a module within the
directory of my Rails app and now, when I call it from a controller, I get the following result written into the file:


Notice that
is now
. Why is that? How can I force Rails to write it as
instead of

This causes me issues because my app is processing the file and when converting it back to a hash, the int is now a string.


It seems that the
gem was not installed. That's strange because both my Ruby script and the Rails version were able to call
gem list
also shown
json 1.8.3
in the list of installed gems. Still, since I ran
gem install json
, everything works as expected. Integers are jsonified as integers.

Can anybody explain why the
require 'json'
in my Ruby script was working even though I couldn't
require 'json'
from irb?

Answer Source

The solution to this is simply to run gem install json even if gem list shows that json is already installed.

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