Creating methods automatically

Greetings,

I am a ruby newbie.
Have a question that, I write a script to access a site’s API, with
httpclient library, and get the response from it.
The response content is just JSON string.

My question is how to let people access the result via method with the
method name is the key in JSON?

For example, I got the response JSON:

{
name: “John Smitp”,
sex: “Male”,
department: “QA”,
}

How do I convert it to an object, when people call obj.name get “John
Smith” etc?

I hope I describe the question clearly.
Thanks in advance.

On Wed, May 14, 2014 at 4:37 PM, Ken P. [email protected] wrote:

For example, I got the response JSON:

{
name: “John Smitp”,
sex: “Male”,
department: “QA”,
}

How do I convert it to an object, when people call obj.name get “John S.”
etc?

There might be other ways, but the json included in the stdlib parses
your json to a Hash. You could then use it with your own custom class
or use OpenStruct to have what you want. Example:

2.0.0p195 :001 > require ‘json’
=> true
2.0.0p195 :021 > require ‘ostruct’
=> false
2.0.0p195 :022 > o = OpenStruct.new JSON.parse(’{“name”:“test”}’)
=> #
2.0.0p195 :023 > o.name
=> “test”

Note: careful that your json above is not valid, since name, sex and
department should be quoted.

Jesus.

Hi Ken, you can do this on Ruby 2.1.1:

require 'json'                       # require the json library
json = JSON.parse('{"name":"John"}') # Parse the json string as a
                                     # Hash
json_struct = OpenStruct.new(json)   # Instantiate an OpenStruct
                                     # object passing the Hash as 

options
puts(json_struct.name) # => “John”

But you should already be able to access all the relevant information
already on the second line, using json["name"] for example, there’s no
need to instantiate the OpenStruct object.

require 'json'                       # require the json library
json = JSON.parse('{"name":"John"}') # Parse the json string as a

puts(json["name"]) # => "John"

Thanks all for the helps.

Regards.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs