Rails/Ruby equivalent of PHP file_get_contents - ruby-on-rails

Would like to know the Rails/Ruby equivalent of the following PHP:
$data = json_decode(file_get_contents(URL_GOES_HERE))
The URL is an external resource that returns json data (Facebook's API).
I've tried:
data = JSON.parse(URL_GOES_HERE)
but I assume I still need the `file_get_contents' part? How do I do this in Rails 4?

Try this
require 'open-uri'
file = open(URL_GOES_HERE)
data = JSON.parse file.read

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.

Rails: How to send a http get request with UTF-8 encoding

I'm trying to use an external API to get some information
address=self.address
response = HTTParty.get("http://api.map.baidu.com/geocoder/v2/?address=#{address}&output=json&ak=5dfe24c4762c0370324d273bc231f45a")
decode_response = ActiveSupport::JSON.decode(response)
However, the address is in chinese, so I need to convert into UTF-8 code,
if not I'll get URI::InvalidURIError (bad URI(is not URI?): How to do it?
I tried address=self.address.force_encoding('utf-8'), but it does not work, maybe I should use other method instead?
UPDATE:
uri = "http://api.map.baidu.com/geocoder/v2/?address=#{address}&output=json&ak=5dfe24c4762c0370324d273bc231f45a"
encoded_uri = URI::encode(uri)
response = HTTParty.get(encoded_uri)
decode_response = ActiveSupport::JSON.decode(response)
self.latitude = decode_response['result']['location']['lat']
and I get can't convert HTTParty::Response into String. What's wrong with it?
I found something here, I think I'll need to tell Httparty explicityly to parse it with JSON?
You could save this to a file 'geo.rb' and run ruby geo.rb
require 'uri'
require 'httparty'
address = "中国上海"
uri = "http://api.map.baidu.com/geocoder/v2/?address=#{address}&output=json&ak=5dfe24c4762c0370324d273bc231f45a"
encoded_uri = URI::encode uri
puts HTTParty.get(encoded_uri)

The most super simple example to start woking with NetHTTP

In Rail my final goal is to write a Net::HTTP client to connect to my REST API that is returning JSON and parse it, pass it to View , etc....
But first things first!
What is the simplest thing I can start with?
I am looking at this page:http://ruby-doc.org/stdlib-1.9.3/libdoc/net/http/rdoc/Net/HTTP.html
and I get the impression that if I have one .rb file with these two lines of code in it, it should show me something?
require 'net/http'
Net::HTTP.get('example.com', '/index.html')
url = URI.parse("http://example.com")
req = Net::HTTP::Get.new(url.path)
#resp = Net::HTTP.new(url.host, url.port).start {|http| http.request(req)}
in a view
<%= "The call to example.com returned this: #{#resp}" %>
You could start testing with something like this:
require 'net/http'
response = Net::HTTP.get_response("www.google.com","/")
puts response.body
I'll recommend you take a look at the docs: Net::HTTPSession

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'

How do I get the contents of an http request in Ruby?

In PHP I can do this:
$request = "http://www.example.com/someData";
$response = file_get_contents($request);
How would I do the same thing in Ruby (or some Rails method?)
I've been googling for a half an hour and coming up completely short.
The standard library package open-uri is what you're after:
require 'open-uri'
contents = open('http://www.example.com') {|io| io.read}
# or
contents = URI.parse('http://www.example.com').read
require 'net/http'
Net::HTTP.get(URI.parse('http://www.example.com/index.html'))
Not sure why I didn't find this earlier. Unless there's an better way, I'm going with this!
Using the net/http library as shown:
require 'net/http'
response = Net::HTTP.get_response('mysite.com','/api/v1/messages')
p response.body
In your view try
<%= request.inspect %>

Resources