Learn how to parse JSON objects with ruby.

JavaScript Object Notation (JSON) is a data exchange format. While originally designed for JavaScript, these days many computer programs interact with the web and use JSON.

Interacting with the web is mostly done through APIs (Application Programmable Interface), in JSON format.

ruby JSON example

Parse JSON

You can parse a JSON object with ruby. The object will then be converted to a ruby object.

Start by creating a json object

1
2
3
4
5
{
"gold": 1271,
"silver": 1284,
"platinum": 1270
}

Then parse the JSON object like this:
1
2
3
4
5
6
7
8
9
10
11
12
# don't forget to install the json module
# gem install json

require 'rubygems'
require 'json'

s = '{"gold":1271,"silver":1284, "platinum": 1270}'
obj = JSON.parse(s)

puts obj["gold"]
puts obj["silver"]
puts obj["platinum"]

Parse JSON from URL

You can get JSON objects directly from the web and convert them to ruby objects. This is done through an API endpoint

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# need modules:
# gem install json
# gem install httparty

require 'httparty'
require 'rubygems'
require 'json'

# get raw json string
endpoint = "https://api.gdax.com/products/BTC-EUR/ticker"
response = HTTParty.get(endpoint)

# parse object
obj = JSON.parse(response.body)

# output object properties
puts obj["price"]
puts obj["volume"]