How to convert a Ruby object to JSON

后端 未结 3 786
我在风中等你
我在风中等你 2020-12-09 01:38

I would like to do something like this:

require \'json\'

class Person
attr_accessor :fname, :lname
end

p = Person.new
p.fname = \"Mike\"
p.lname = \"Smith\         


        
3条回答
  •  粉色の甜心
    2020-12-09 02:26

    Try it. If you're using Ruby on Rails (and the tags say you are), I think this exact code should work already, without requiring anything.

    Rails supports JSON output from controllers, so it already pulls in all of the JSON serialization code that you will ever need. If you're planning to output this data through a controller, you might be able to save time by just writing

    render :json => @person
    

提交回复
热议问题