简体   繁体   中英

Ruby on Rails - how to parse this object

I am making a call to a REST API and I get back a bunch of values. I am trying to figure out how to parse them.

Here are the values:

#<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">

How would a parser look like? I am pretty new to Ruby and the stuff returned is kind of difficult to make sense of, so I am not certain how/where to start.

So far I have something like:

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

  end
  rescue Exception => ex
    # Do something
  end

Thanks in advance for the suggestions.

In a rails app, once you have the JSON, you can just do:

decoded_json = ActiveSupport::JSON.decode(json)

decoded_json will be a hash, and you can access the values using the keys from the json, for example:

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

You could also consider using something like HTTParty to deal with your communications with the RESTful API, as described here: http://mike.bailey.net.au/2011/02/json-with-ruby-and-rails/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM