2014-07-10 5 views
0

외부 서비스 JSON에서 my current_user에 대한 교육 정보 (전자 메일)를받습니다.컬렉션이있는 json 배열을 가진 발표자에게 구문 분석하는 방법은 무엇입니까?

{ 
    “id:”5357c5d17303b5357c5d173078”, 
    “email”:”[email protected]”, 
    ”trainings”:[ 
     { 
      “training_id“: “5357c4e5d61f15357c4e5d622f“, 
      “name”: ”training 1”, 
      “state”: “started” 
     }, 
     { 
      “training_id“: “5357af490fcda5357af490fd15“, 
      “name”: ”training 2”, 
      “state”: “finished” 
     } 
    ] 
} 

이 JSON을 구문 분석하여 내 페이지에 표시하고 싶습니다. 그래서 발표자에 대해 생각했습니다.

class EducationPresenter 
    attr_reader :email, :trainings 

    def initialize json 
    @email = json['email'] 
    @trainings = json['trainings'] 
    end 
end 

그래서 지금은 그렇게 내보기에 그것을 사용할 수 있습니다

Email: <%= @presenter.email %> 
<% @presenter.trainings.each do |training| %> 
Training: <%= training['training_id'] %> 
<% end %> 

나는 또한 구문 분석하고 어떤 객체에 JSON 변환 할 수있는 방법이처럼 사용할 수 있도록 :

@presenter.training.each {|t| t.state } 

발표자 님이이를 처리 할 수 ​​있습니까?

답변

0

사용 JSON::parse :

class EducationPresenter 
    attr_reader :presneter 

    def initialize json 
    json_hash = JSON.parse(json) 
    @presneter = OpenStruct.new(
           email: json_hash['email'], 
           trainings: json_hash['trainings'] 
           ) 
    end 
end 

읽기 Parsing JSON이 또한 OpenStruct을 이해합니다. 이제 당신이 당신의 객체를 생성

,

@education_presenter = EducationPresenter.new(json_string) 

그리고보기 :

Email: <%= @education_presenter.presenter.email %> 
<% @education_presenter.presenter.trainings.each do |training| %> 
Training: <%= training['training_id'] %> 
<% end %>