How to convert a Ruby object to JSON

后端 未结 3 826
我在风中等你
我在风中等你 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:13

    To make your Ruby class JSON-friendly without touching Rails, you'd define two methods:

    • to_json, which returns a JSON object
    • as_json, which returns a hash representation of the object

    When your object responds properly to both to_json and as_json, it can behave properly even when it is nested deep inside other standard classes like Array and/or Hash:

    #!/usr/bin/env ruby
    
    require 'json'
    
    class Person
    
        attr_accessor :fname, :lname
    
        def as_json(options={})
            {
                fname: @fname,
                lname: @lname
            }
        end
    
        def to_json(*options)
            as_json(*options).to_json(*options)
        end
    
    end
    
    p = Person.new
    p.fname = "Mike"
    p.lname = "Smith"
    
    # case 1
    puts p.to_json                  # output: {"fname":"Mike","lname":"Smith"}
    
    # case 2
    puts [p].to_json                # output: [{"fname":"Mike","lname":"Smith"}]
    
    # case 3
    h = {:some_key => p}
    puts h.to_json                  # output: {"some_key":{"fname":"Mike","lname":"Smith"}}
    
    puts JSON.pretty_generate(h)    # output
                                    # {
                                    #   "some_key": {
                                    #     "fname": "Mike",
                                    #     "lname": "Smith"
                                    #   }
                                    # }
    

    Also see "Using custom to_json method in nested objects".

提交回复
热议问题