简体   繁体   中英

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?

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

Gah, it was my own stupid fault. "as_json" turns something into a literal ruby json object (which is a hash). "to_json" turns it into a json string that non-ruby languages can read. Bah.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM