how deserialize a json in rails - ruby-on-rails

I send a http request and get a json for response like below:
{"total":"1200.0","used":"35.0","available":1165.0}
now I want deserialize this json and show to user in a table like below:
total : 1200
used : 35
availabele : 1165
I use JSON.parse(response),but I get below error:
no implicit conversion of Net::HTTPOK into String
How can I do this?

Net::HTTP has responses in body. so, Try
JSON.parse response.body

You have to pass the response.body as the parameters into the JSON.parse method then assign the method to a variable to use elsewhere in your code.
parse_res = JSON.parse(res.body)

Related

ruby-saml SAMLRequest as POST instead of GET

I am starting to use ruby-saml for one of the projects. IDP that I am using is expecting POST for authentication request with HTTP body containing SAMLRequest. Looking at the source code for authrequest.rb, create method can only do GET instead of POST.
I decided to call the create_params and get the base64 token which I can use from my view to do a POST.
When I use the following code
params = {}
request = OneLogin::RubySaml::Authrequest.new
token = request.create_params(saml_settings, params)
p token
p token["SAMLRequest"]
p decode(token["SAMLRequest"])
When i try base64decode.org or call the decode method, I get encoding for is not correct.
1) Can I do a POST instead of a GET?
2) What am I doing wrong in creating the request for it to be bad encoding?
thanks
1) Can I do a POST instead of a GET?
Yes, but support POST-binding is not just replace GET parameters by POST parameters...the signature on POST-binding is embed on the SAML message and is not another GET parameter.
2) What am I doing wrong in creating the request for it to be bad encoding?
thanks
The AuthNRequest is not only base64encoded, but also deflated.
Try use Base64 Decode + Inflate
You will find that thread interesting:
https://github.com/onelogin/ruby-saml/issues/124

Get request response is in weird format

I send a get request to a local (separate from app) jetty web server
RestClient.get("ip/command/core/get-version", {})
Then I do a JSON.parse() on the response.
As a result I get
{"revision"=>"r2407", "full_version"=>"2.5 [r2407]", "full_name"=>" [r2407]", "version"=>"2.5"}
What's wrong? How do I turn it into a hash, so I can extract the full_version property?
String returned by service is html encoded. Try decoding it first:
JSON.parse(CGI.unescape_html(response_body))
Your JSON response looks to be encoded into HTML entities.
If you are using Ruby, try decoding the response using CGI.unescape_html prior to running JSON.parse. Running the result of that method through JSON.parse should give you your hash.

Convert Rails Net::HTTP request to MD5 Hex Digest

In order to use a third-party API, I need to encode the Net::HTTP::Post request as an MD5 hex digest, which is then used as part of the signature. However, when I try to simply Digest::MD5.hexdigest(req), it throws a "Cannot convert to string error", and when I explicitly req.to_s, it just gives the MD5 of #<Net::HTTP::Post:0x112a0eef8>
I'm simply:
request = Net::HTTP::Post.new(url.path)
request.body = {
"key" => "val"
}.to_json
# later...
hexDigest = Digest::MD5.hexdigest(request)
which is the documented spec, I think: "[with the] JSON body containing the new information."
This is the relevant sample Java code they supply:
ByteArrayOutputStream requestOutputStream = new ByteArrayOutputStream();
httpMethod.getEntity().writeTo(requestOutputStream);
DigestUtils.md5Hex(requestOutputStream.toByteArray()).toLowerCase();
Any ideas?
Thanks!
Try to call 'to_s' method explicitly, it should help:
hexDigest = Digest::MD5.hexdigest(request.to_s)
The equivalent ruby code for those lines is:
OpenSSL::Digest::MD5.hexdigest(request.body)
httpMethod.getEntity() will return the json defined as the request body.
requestOutputStream.toByteArray() will return the array of bytes corresponding to the request body.

Trouble handling HTTP responses and parsing JSON data

I am using Ruby on Rails 3 and I would like to solve an issue with the following code where a web client application receive back some JSON data from a web service application that uses a Rack middleware in order to respond.
In the web client app model I have
response_parsed = JSON.parse(response.body)
if response_parsed["account"]
...
else
return response
end
In the above code the response.body come back from the web service app that uses a Rack middleware to respond to the web client:
accounts = Account.where(:id => ids)
[200, {'Content-Type' => 'application/json'}, accounts.to_json] # That is, response.body = accounts.to_json
Data transmission is ok, but I get the following error
TypeError
can't convert String into Integer
*Application Trace*
lib/accounts.rb:107:in `[]'
The line 107 corresponds to
if response_parsed["account"]
...
Where and what is the problem? How to solve that?
If I try to debug the respons.body I get
# Note: this is an array!
"[{\"account\":{\"firstname\":\"Semio\",\"lastname\":\"Iaven\"\"}}]"
If I'm saying something you already realize, forgive me.
It looks like your response is a one-element array with a hash in it as the first element. Because the response is an array, when you use the [] it is expecting a integer representing the index of the item in the array you'd like to access, and that is what the error message means--it expected that you'd tell it the integer value of the item you wanted, but instead you gave it a string.
If you instead do:
response_parsed[0]['account']
It seems like you'd get what you want.

Ruby Net::HTTP::Get and JSON responses

I'm trying to connect to an API and retrieve the json results with my rails app, however it doesn't seem to work.
Take for example:
#request = Net::HTTP::Get.new "http://example.com/?search=thing&format=json"
When I try the url in my browser it works! and I get JSON data, however when I try that in Ruby the body is nil.
>> y #request
--- !ruby/object:Net::HTTP::Get
body:
body_stream:
header:
accept:
- "*/*"
user-agent:
- Ruby
method: GET
path: http://example.com/?search=thing&format=json
request_has_body: false
response_has_body: true
Any thoughts?
I usually use open-uri
require 'open-uri'
content = open("http://your_url.com").read
`
You need to actually send the request and retrieve a response object, like this:
response = Net::HTTP.get_response("example.com","/?search=thing&format=json")
puts response.body //this must show the JSON contents
Regards!
PS: While using ruby's HTTP lib, this page has some useful examples.

Resources