Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails "as_json" method returning invalid json?

I am trying to have a iOS application read json generated by a rails server. For now, I am just having it be a text file, but the eventual goal is for it to be retrieved via a route.

The iOS application is throwing errors trying to read (which was generated with as_json):

{"created_at"=>Fri, 16 Aug 2013 13:21:07 UTC +00:00, "gender"=>"M", "id"=>1, "location_id"=>1, "max_hit_points"=>nil, "my_name"=>"Jim Bob", "npc_type_id"=>nil, "universe_id"=>1, "updated_at"=>Fri, 16 Aug 2013 13:21:07 UTC +00:00} 

when I give that to a json validator (http://jsonformatter.curiousconcept.com)

I get several errors about nearly everything, especially how it has "=>" rather than a colon.

Am I doing something completely weird? Why does rails seem to not generate valid json? Are there somehow multiple types of valid json (arrows vs colons?) How can I make it generate json that the iOS app (or that validator) likes?

like image 830
J.R. Avatar asked Aug 25 '26 01:08

J.R.


1 Answers

as_json is used to prepare a hash suitable for json rendering. (see doc)

You need to call to_json to get the real json string.

For example :

your_object.as_json.to_json

More info on the difference and the implications can be found here

like image 192
Intrepidd Avatar answered Aug 26 '26 16:08

Intrepidd