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?
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:
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"