Ruby objects and JSON serialization (without Rails)

前端 未结 11 1964
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-28 03:32

I\'m trying to understand the JSON serialization landscape in Ruby. I\'m new to Ruby.

Is there any good JSON serialization options if you are not working with Rails?

11条回答
  •  盖世英雄少女心
    2020-11-28 04:21

    Check out Oj. There are gotchas when it comes to converting any old object to JSON, but Oj can do it.

    require 'oj'
    
    class A
        def initialize a=[1,2,3], b='hello'
            @a = a
            @b = b
        end
    end
    
    a = A.new
    puts Oj::dump a, :indent => 2
    

    This outputs:

    {
      "^o":"A",
      "a":[
        1,
        2,
        3
      ],
     "b":"hello"
    }
    

    Note that ^o is used to designate the object's class, and is there to aid deserialization. To omit ^o, use :compat mode:

    puts Oj::dump a, :indent => 2, :mode => :compat
    

    Output:

    {
      "a":[
        1,
        2,
        3
      ],
      "b":"hello"
    }
    

提交回复
热议问题