Ruby objects and JSON serialization (without Rails)

前端 未结 11 1903
爱一瞬间的悲伤
爱一瞬间的悲伤 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:06

    Jbuilder is a gem built by rails community. But it works well in non-rails environments and have a cool set of features.

    # suppose we have a sample object as below
    sampleObj.name #=> foo
    sampleObj.last_name #=> bar
    
    # using jbuilder we can convert it to json:
    Jbuilder.encode do |json|
      json.name sampleObj.name
      json.last_name sampleObj.last_name
    end #=> "{:\"name\" => \"foo\", :\"last_name\" => \"bar\"}"
    
    0 讨论(0)
  • 2020-11-28 04:07
    require 'json'
    {"foo" => "bar"}.to_json
    # => "{\"foo\":\"bar\"}"
    
    0 讨论(0)
  • 2020-11-28 04:10

    To get the build in classes (like Array and Hash) to support as_json and to_json, you need to require 'json/add/core' (see the readme for details)

    0 讨论(0)
  • 2020-11-28 04:20

    If rendering performance is critical, you might also want to look at yajl-ruby, which is a binding to the C yajl library. The serialization API for that one looks like:

    require 'yajl'
    Yajl::Encoder.encode({"foo" => "bar"}) #=> "{\"foo\":\"bar\"}"
    
    0 讨论(0)
  • 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"
    }
    
    0 讨论(0)
  • 2020-11-28 04:24

    Since I searched a lot myself to serialize a Ruby Object to json:

    require 'json'
    
    class User
      attr_accessor :name, :age
    
      def initialize(name, age)
        @name = name
        @age = age
      end
    
      def as_json(options={})
        {
          name: @name,
          age: @age
        }
      end
    
      def to_json(*options)
        as_json(*options).to_json(*options)
      end
    end
    
    user = User.new("Foo Bar", 42)
    puts user.to_json #=> {"name":"Foo Bar","age":42}
    
    0 讨论(0)
提交回复
热议问题