Development Tip

Ruby 객체 및 JSON 직렬화 (Rails 제외)

yourdevel 2020. 11. 7. 10:34
반응형

Ruby 객체 및 JSON 직렬화 (Rails 제외)


Ruby의 JSON 직렬화 환경을 이해하려고합니다. 저는 Ruby를 처음 사용합니다.

Rails로 작업하지 않는 경우 좋은 JSON 직렬화 옵션이 있습니까?

이것이이 대답이 (Rails로)가는 곳인 것 같습니다 . Ruby 객체를 JSON으로 변환하는 방법

json gem은 자신의 to_json 메소드를 작성해야하는 것처럼 보이게하는 것 같습니다. to_json이 배열 및 해시로 작업하도록 할 수 없었습니다 (문서에 따르면 이것으로 작동 함). json gem이 객체를 반영하지 않고 기본 직렬화 전략을 사용하지 않는 이유가 있습니까? 이것이 to_yaml 작동 방식이 아닙니까 (여기에서 추측)


JSON 라이브러리를 사용하려면 libjson-ruby패키지 관리자에서 설치해야 할 수 있습니다 .

'json'라이브러리를 사용하려면 :

require 'json'

객체를 JSON으로 변환하려면 (이 세 가지 방법은 동일합니다) :

JSON.dump object #returns a JSON string
JSON.generate object #returns a JSON string
object.to_json #returns a JSON string

JSON 텍스트를 객체로 변환하려면 (이 두 가지 방법은 동일합니다) :

JSON.load string #returns an object
JSON.parse string #returns an object

자신의 클래스의 객체에 대해서는 조금 더 어려울 것입니다. 다음 클래스의 경우 to_json은 "\"#<A:0xb76e5728>\"".

class A
    def initialize a=[1,2,3], b='hello'
        @a = a
        @b = b
    end
end

이것은 아마도 바람직하지 않습니다. 객체를 JSON으로 효과적으로 직렬화하려면 자체 to_json 메서드를 만들어야합니다. 이를 위해 from_json 클래스 메소드가 유용합니다. 다음과 같이 클래스를 확장 할 수 있습니다.

class A
    def to_json
        {'a' => @a, 'b' => @b}.to_json
    end
    def self.from_json string
        data = JSON.load string
        self.new data['a'], data['b']
    end
end

'JSONable'클래스에서 상속하여이를 자동화 할 수 있습니다.

class JSONable
    def to_json
        hash = {}
        self.instance_variables.each do |var|
            hash[var] = self.instance_variable_get var
        end
        hash.to_json
    end
    def from_json! string
        JSON.load(string).each do |var, val|
            self.instance_variable_set var, val
        end
    end
end

그런 다음을 사용 object.to_json하여 JSON으로 직렬화 object.from_json! string하고 JSON 문자열로 저장된 저장된 상태를 객체에 복사 할 수 있습니다 .


Oj를 확인하십시오 . 오래된 객체를 JSON으로 변환하는 데 문제가 있지만 Oj는 할 수 있습니다.

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

결과는 다음과 같습니다.

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

^o객체의 클래스를 지정하는 데 사용하고, 원조 직렬화에 존재한다. 을 생략하려면 다음 모드를 ^o사용 :compat하십시오.

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

산출:

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

렌더링 성능이 중요한 경우 C yajl 라이브러리에 대한 바인딩 인 yajl-ruby 를 살펴볼 수도 있습니다 . 이를위한 직렬화 API는 다음과 같습니다.

require 'yajl'
Yajl::Encoder.encode({"foo" => "bar"}) #=> "{\"foo\":\"bar\"}"

어떤 버전의 Ruby를 사용하고 있습니까? ruby -v당신에게 말할 것입니다.

1.9.2 인 경우 JSON이 표준 라이브러리에 포함됩니다 .

1.8.something을 사용하는 경우 수행하면 gem install json설치됩니다. 그런 다음 코드에서 다음을 수행하십시오.

require 'rubygems'
require 'json'

그런 다음 to_json개체에 추가 하면 좋습니다.

asdf = {'a' => 'b'} #=> {"a"=>"b"}
asdf.to_json #=> "{"a":"b"}"

Ruby Object를 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}

require 'json'
{"foo" => "bar"}.to_json
# => "{\"foo\":\"bar\"}"

If you're using 1.9.2 or above, you can convert hashes and arrays to nested JSON objects just using to_json.

{a: [1,2,3], b: 4}.to_json

In Rails, you can call to_json on Active Record objects. You can pass :include and :only parameters to control the output:

@user.to_json only: [:name, :email]

You can also call to_json on AR relations, like so:

User.order("id DESC").limit(10).to_json

You don't need to import anything and it all works exactly as you'd hope.


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)


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\"}"

Actually, there is a gem called Jsonable, https://github.com/treeder/jsonable. It's pretty sweet.


I used to virtus. Really powerful tool, allows to create a dynamic Ruby structure structure based on your specified classes. Easy DSL, possible to create objects from ruby hashes, there is strict mode. Check it out.

참고URL : https://stackoverflow.com/questions/4464050/ruby-objects-and-json-serialization-without-rails

반응형