Ruby on Rails - 如何解析这个对象

时间:2012-05-16 18:11:18

标签: ruby-on-rails ruby

我正在调用REST API,然后我回到了一堆值。我试图弄清楚如何解析它们。

以下是值:

#<User _id: 4f8de8c40a5dcd0d1d00004c, agency_requested: [], encrypted_password: "$2a$10$FPVJDLkkD6AXd5SY/hL6KeuC6QR6vfU3OKI3oGCPxrTiEnAwvGOOu", avatar_file_size: nil, avatar_file_name: nil, agreed_to_terms: ["v1"], location: nil, last_name_first_initial: "Genadinik, A.", first_initial_last_name: "A. Genadinik", legacy_blogger_id: nil, created_at: Tue Apr 17 22:03:50 UTC 2012, active_advertiser_id: nil, avatar_source: :default, agency_roles: [], last_sign_in_ip: "127.0.0.1", confirmation_sent_at: Tue Apr 17 22:03:50 UTC 2012, created_via: "CMPLY-WEB", deleted_at: nil, updated_at: Fri May 11 16:37:16 UTC 2012, last_sign_in_at: Thu May 10 20:48:53 UTC 2012, display_welcome_help: true, program_influencers: [], agency_rep: true, account_type: :influencer, legacy_user_id: nil, sign_in_count: 44, _type: nil, avatar_content_type: nil, programs: [], active_agency_id: nil, account_status: :active, admin_roles: [], legacy_password: nil, gets_newsletter: false, full_name: "Alex Genadinik", last_name: "Genadinik", reset_password_token: nil, current_sign_in_ip: "127.0.0.1", authentication_token: "ViQ5q89n39zyyVUT3wLp", user_name: "me_n0_like_scrennames", time_zone: "Chihuahua", bio: nil, reset_password_sent_at: nil, current_sign_in_at: Fri May 11 16:37:16 UTC 2012, confirmation_token: nil, avatar_updated_at: nil, last_name_first_name: "Genadinik, Alex", agency_id: nil, first_name: "Alex", confirmed_at: Tue Apr 17 22:49:28 UTC 2012, email: "alex@cmp.ly">

解析器的外观如何?我对Ruby很陌生,返回的东西很难理解,所以我不确定如何/从哪里开始。

到目前为止,我有类似的内容:

  begin
    // But not sure how to loop through this stuff and extract the values.

  end
  rescue Exception => ex
    # Do something
  end

提前感谢您的建议。

1 个答案:

答案 0 :(得分:1)

在rails应用程序中,一旦你拥有了JSON,你就可以这样做:

decoded_json = ActiveSupport::JSON.decode(json)

decoding_json将是一个哈希,你可以使用json中的键来访问这些值,例如:

decoded_json["_id"]
decoded_json["location"]

您还可以考虑使用类似HTTParty的东西来处理与RESTful API的通信,如下所述: http://mike.bailey.net.au/2011/02/json-with-ruby-and-rails/