How to include JSON response.body in string
I am working on parsing JSON in Ruby. Can someone let me know how to grab response.body
and post it inside a string.
Are there any gems for sorting this information through parsing?
require 'net/http'
require 'json'
uri = URI('https://api.wmata.com/StationPrediction.svc/json/GetPrediction/all')
uri.query = URI.encode_www_form({
# Specify your subscription key
'api_key' => '#',
})
request = Net::HTTP::Get.new(uri.request_uri)
# Basic Authorization Sample
# request.basic_auth 'username', 'password'
response = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') do |http|
http.request(request)
@data = response
end
source to share
The JSON gem is smart and makes it easy to convert an object to JSON, or convert a JSON string back to an object. This is a simple round trip example:
require 'json'
foo = {'a' => 1, 'b' => [2, 3]}
json_string = JSON[foo]
json_string # => "{\"a\":1,\"b\":[2,3]}"
bar = JSON[json_string] # => {"a"=>1, "b"=>[2, 3]}
bar == foo # => true
Note what JSON\[...\]
determines whether the parameter is a string or a hash (or an array). If it is the first, it tries to convert the string to a hash or array, or vice versa. From the documentation:
If the object is a string, parse the string and return the parsed result as a Ruby data structure. Otherwise, create JSON text from a Ruby data structure object and return it.
You can use the method to_json
if you want to convert the object as well:
foo.to_json # => "{\"a\":1,\"b\":[2,3]}"
There are questions you should be aware of when using to_json
it as it will generate invalid JSON output unless you give it an array or hash:
'a'.to_json # => "\"a\""
1.to_json # => "1"
JSON.parse(...)
can also be used to return a string to an object:
JSON.parse(json_string) # => {"a"=>1, "b"=>[2, 3]}
but I tend to use the shorter one JSON[...]
.
source to share