I want to use an external API in Ruby that makes an HTTP request and returns JSON. I want to get a hash that can be used in Ruby from JSON.
#Load various libraries
require 'net/http'
require 'json'
require 'uri'
#uri library>URI module
#Generate and return the corresponding instance
uri = URI.parse('http://hoge.com')
# => #<URI::HTTP http://hoge.com>
#net/http library>Net::HTTP class
#Send a GET request to the URL and send the body"String"Returns as.
json = Net::HTTP.get(uri)
#joson library>JSON module
#Convert the obtained JSON format character string to a Ruby object and return it
JSON.parse(json)
With the above, you can send a GET request to the URL and get a hash that can use JSON format data in Ruby.
URI Module Net :: HTTP class JSON module
JavaScript Object Notation (JSON, Jason) is one of the data description languages. It is a lightweight text-based data exchange format that can be used in any programming language [1]. The name and syntax are derived from the notation of objects in JavaScript. https://ja.wikipedia.org/wiki/JavaScript_Object_Notation
It is used not only for JavaScript but also for data exchange between various languages such as Java, PHP, Ruby, Python, especially Ajax and REST API. In the past, XML was used as a common data definition language, but nowadays, simple JSON is increasingly used. http://www.tohoho-web.com/ex/json.html
It is a description format for exchanging data between different languages, and the notation is derived from JavaScript. In the past, XML was used when exchanging data, and JSON is now the mainstream.
A colon is attached to the key and value.
Enclose the string in " "
double quotes.
{ "hoge": "fuga" }
Single quotes cannot be used.
❌{ 'hoge': 'fuga' }
You can specify multiple keys and values by using commas
{ "hoge": "fuga", "foo": 123 }
Only arrays and values are OK!
["hoge","fuga"] "hoge" 123
I got JSON from API and briefly summarized how to use it in Ruby and JSON.
Recommended Posts