Ruby SQS Parsing Message? - ruby-on-rails

Initially I sent the converted object using .to_json which gives me a string I sent this to sqs. Now i'm retrieving the message and now it's in string form? How do I parse it back into my inital object?
--Edit
Ruby on Rails. I'm using a library to contact sqs and send the object over. Before I send it, I convert it using .to_json. Then Now, I'm writing a backend.rb file that uses that library and receives the msg and if there is a msg i want it to convert that msg back into a #project then I plan to send this #project over to a template .erb file.

To turn a JSON string into Ruby objects, call JSON.parse like so:
require 'json'
JSON.parse( '{"foo":"bar"}' )
#=> {"foo"=>"bar"}
a = JSON.parse( '[1,2,3] )
#=> [1, 2, 3]
JSON.parse( '{"name":"Gavin","cats":["Phleep","Tessa"]}' )
#=> {"name"=>"Gavin", "cats"=>["Phleep", "Tessa"]}

Related

Read JSON formatted response from Google finance api

The code for get data from google-finance url:
uri =URI.parse('http://finance.google.com/finance/info?client=i&q=NSE:ANDHRABANK')
rs = Net::HTTP.get(uri)
rs.delete! '//'
a = JSON.parse(rs)
p a
This is the response:
[{"id"=>"15355585", "t"=>"ANDHRABANK", "e"=>"NSE", "l"=>"49.30", "l_fix"=>"49.30", "l_cur"=>"₹49.30", "s"=>"0", "ltt"=>"3:30PM GMT+5:30", "lt"=>"Jan 13, 3:30PM GMT+5:30", "lt_dts"=>"2017-01-13T15:30:00Z", "c"=>"-0.15", "c_fix"=>"-0.15", "cp"=>"-0.30", "cp_fix"=>"-0.30", "ccol"=>"chr", "pcls_fix"=>"49.45"}]
Unable to access the JSON array. Want to access the array in a['t'] manner.
Since you're dealing with a hash in an array, you have to specify the array element position as well:
require 'json'
require 'net/http'
uri = URI.parse('http://finance.google.com/finance/info?client=i&q=NSE:ANDHRABANK')
rs = Net::HTTP.get(uri)
rs.delete! '//'
a = JSON.parse(rs)
p a.class #=> Array
p a[0]["t"] #=> "ANDHRABANK"
Either you run loop on array then you can access using a[i]["t"] or use a[0]["t"].
Note: i is the index of array elements.
You aren't making it easy for yourself. Consider this:
require 'json'
require 'open-uri'
rs = open('http://finance.google.com/finance/info?client=i&q=NSE:ANDHRABANK').read
foo = JSON[rs[4..-1]].first
foo['t'] # => "ANDHRABANK"
Rather than deal with the intricacies of Net::HTTP, which is more useful as a tool to build new HTTP services, I'd recommend relying on OpenURI, or one of the many HTTP clients available. The advantage over Net::HTTP is redirection is automatically handled plus simplicity. OpenURI does have some downsides, but for a basic URL getter it's fine.
The JSON class has [] which is smart enough to convert a string into the corresponding Ruby object. It'll also serialize a Ruby object back into a String:
puts JSON[{'a' => 1}]
# >> {"a":1}
The service you're calling is returning JSON, only, in this case, it's a single-element array containing a hash. Using first makes it easy to retrieve the hash and access it normally. It's cleaner to do that than to sprinkle your code with this form:
foo[0]['t']
which is longer to type and results in a visual noise.

how deserialize a json in 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)

743: unexpected token at '... in Ruby on Rails

I saved a file named array.json on my Dropbox folder and i access to it via Dropbox API. All works fine, but when i retrieve JSON content i cannot JSON.parse that string!!
session = DropboxSession.new(APP_KEY, APP_SECRET)
session.set_access_token(ACCESS_TOKEN_KEY, ACCESS_TOKEN_SECRET)
client = DropboxClient.new(session, ACCESS_TYPE)
json = client.get_file(DIRECTORY + '/array.json')
#json = JSON.parse json
Error:
743: unexpected token at '{"Nome" : "Mario Rossi",
"C.F." : "ABCDEFGHILMNOP",
"Booking Assistance" : "MARIO",
"Status of reservation" : "25/11/2011"}'
JSON string is valid!! if i copy this string and paste it (manually) as parameter in JSON.parse(), json is parsed correctly!! So i think is a encoding problem...but where i wrong?
We have abandoned the json parsing backend that is the default in Rails. The default backend is YAML based and imo a useless mess. After several gotchas parsing unicode, and dates in some cases, we discovered that the backend can be replaced via configuration.
You can substitute the parsing backend in an initializer
ActiveSupport::JSON.backend = "JSONGem"
There are several gems that can be used as the backend, we just use the json gem
gem 'json'

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.

RoR: to_json on an array of hashes

I have an array of hashes in a Rails action which i return to client in json format:
{"msg": "Got report data.Check 'report' json object. ", "success": true, "reports": "[{\"total_transfers\": 0, \"total_keywords\": 0, \"keyword\": \"plum\", \"total_duration\":1464.0, \"total_calls\": 22, \"total_sms\": 0, \"avg_duration\": 67,\"total_email\": 0}]"}
In action i do: return reports.to_json but as you can see it does not look like valid json (why the escape characters?)
In client side js code, i do reports.length and get 163??? when it should say 1 because there is only one "report" in the reports array.
As you can see "reports" is one big string, instead of an array of a hash which you'd expect (163 is the length of the string, and this is why you can see escape characters). Which json library are you using with rails? What kind of object is your array of hash exactly? It might not have the to_json method implemented...
Alternatively you might try to convert your repsonse to yaml first, from that getting json is easier.
reports_array_object = eval("(" + reports + ")");
sweet!!!!

Resources