I am working on parsing JSON in Ruby. Can someone let me know how to take response.body
and post it inside string.
Are there any gems available to sort this information via 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
Users can also Convert JSON File to Text by uploading the file. Download converted file with txt extension. JSON to Text Online works well on Windows, MAC, Linux, Chrome, Firefox, Edge, and Safari.
// creating object of Gson Gson gson = new Gson(); // calling method fromJson and passing JSON string into object // The first parameter is JSON string // The second parameter is the Java class to parse the JSON into an instance of. object = gson. fromJson(jsonString,GFG. class);
structure your data: break the multiline string into an array of strings, and then join them later on. Try hjson tool. It will convert your multiline String in json to proper json-format.
The JSON.stringify() method converts a JavaScript value to a JSON string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified.
You can convert JSON response to hash with:
hash_response = JSON.parse(response)
After that you can easily use hash in ruby functions.
The JSON gem is smart and makes it really easy to convert an object to JSON, or convert the 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 that JSON\[...\]
senses whether the parameter is a string or a hash (or array). If it's the first it tries to convert the string to a hash or array, or, vice versa. From the documentation:
If object is string-like, parse the string and return the parsed result as a Ruby data structure. Otherwise generate a JSON text from the Ruby data structure object and return it.
You can use the to_json
method if you'd like to convert an object also:
foo.to_json # => "{\"a\":1,\"b\":[2,3]}"
There are gotchas you have to be aware of using to_json
as it will generate invalid JSON output if you don't give it an array or a hash:
'a'.to_json # => "\"a\""
1.to_json # => "1"
JSON.parse(...)
can also be used to turn the string back to an object:
JSON.parse(json_string) # => {"a"=>1, "b"=>[2, 3]}
but I tend to use the shorter JSON[...]
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With