In ruby read json file is very easy. In this article we will explain how to read a JSON file from the disk and use it in ruby.

What is JSON?
JSON is a data exchange format used all over the internet. JSON (JavaScript Object Notation) can be used by all high level programming languages.

How to use JSON with ruby?
The way this works is by first having a json file on your disk.
The program then loads the file for parsing, parses it and then you can use it.

ruby read json

JSON file

Create a file on your disk (name it: example.json). The ruby program below reads the json file and uses the values directly.

The file can contain a one liner. The file content of example.json is:

1
{"usd":1,"eur":1.2,"gbp": 1.2}

Save the file to example.json.

ruby Example

Then create the program below and run it.:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# need to have json module:
# gem install json
#
# create file example.json with
# {"usd":1,"eur":1.2 "gbp": 1.2}

require 'rubygems'
require 'json'

# get json string
s = File.read("example.json")

# parse and convert JSON to Ruby
obj = JSON.parse(s)

# show object values
puts obj["usd"]
puts obj["eur"]
puts obj["gbp"]

The above program will open the file ‘example.json’ and parse it. You can access the JSON data like any variables.