ilovebigmacs
ilovebigmacs

Reputation: 993

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 to_json method.

In the file, I get the following result:

{"name":"Bob","age":42}

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

{"name":"Bob","age":"42"}

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

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.

EDIT

It seems that the json gem was not installed. That's strange because both my Ruby script and the Rails version were able to call to_json. 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 to_json and require 'json' in my Ruby script was working even though I couldn't require 'json' from irb?

Upvotes: 2

Views: 147

Answers (1)

ilovebigmacs
ilovebigmacs

Reputation: 993

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

Upvotes: 0

Related Questions