This tutorial explains how to read and write json files in Ruby with examples.

In Ruby, You can read and write ruby files using the gem json module.

First, Install json module in a project.

gem install json

Once installed, You can write a code.

Let’s declare an employee.json file.

{
   "name": "John",
   "salary:1,
   "department":"sales",
   "active": true,
   "roles":[
      "admin",
      "employee",
      "user",
      "visitor"
   ],
   "permanentaddress":{
      "city":"Texas",
      "zipcode":"12345"
   },
   "temporaryaddress":{
      "city":"Denver",
      "zipcode":"84321"
   }
}

Ruby provides a hash data structure to store the json content.

How to read JSON file in Ruby

Following are steps to read the file in Ruby and Railslanguage

  • First, Import the json module into a code, this module provides a code to read the data as hash and convert the hash object to json content.
require 'json'
  • Next, Read the json file using File.read, which takes a file path as a parameter
  jsonData = File.read(json_file)

if the read operation is successful, json content is saved to a variable

  • After the file is read, convert the file content to a Ruby hash object using JSON.parse(jsonData)
  jsonHash = JSON.parse(jsonData)

Now, jsonHash is a ruby hash, that contains content from json file

  • you can access hash object data using the below syntax.
puts jsonHash['name']
puts jsonHash['roles']
puts jsonHash['permanentaddress']['city']
puts jsonHash['temporaryaddress']['city']
  • To hand file operations failures, Begin block used to include a code that throws errors, similar to try in java rescue block includes for handling errors, similar to the catch block in java
    • Errno::ENOENT: throws an error if the file not found
    • JSON::ParserError: throws if an json content is not able to parse to Hash object
    • StandardError => e: to handle io and network failures.

Here is a complete example.

require 'json'

jsonFile = 'employee.json'

begin
  # read the json file into a variable
  jsonData = File.read(jsonFile)
  # Convert the json content into a hash variable
  jsonHash = JSON.parse(jsonData)
  # Convert the json content into a hash variable
  puts parsed_data
  puts jsonHash['name']
  puts jsonHash['roles']
  puts jsonHash['permanentaddress']['city']
  puts jsonHash['temporaryaddress']['city']

rescue Errno::ENOENT
  puts "File not found error."
rescue JSON::ParserError
  puts "Unable to Parse the json file."
rescue StandardError => e
  puts "Other errors #{e.message}"
end

How to write hash object to json file in Ruby

This example initializes a hash object and writes to a json file.

  • import json module into a code
require 'json'
  • Next, Create a Hash object variable with data initialization
data = {
   "name" => "John",
   ......
   ...... more data
}
  • Next, Convert Has object JSOn using JSON.pretty_generate() or JSON.generate()

JSON.generate(): Convert the data json with default formatting, JSON.pretty_generate(): Convert the data into Beautiful pretty printed format json, Pretty print is useful with nice formatting for readability with line breaks and tabs formatting.

Use File.write() to write to a file and use the below code

File.write('result.json', JSON.pretty_generate(data))

Begin and rescue are used to handle errors

  • JSON::GeneratorError: This error is thrown when the hash object is unable to convert to valid JSOn with the JSON.generate() or JSON.pretty_generate() methods

  • Errno::EACCES: This error is thrown if there is a permission issue for writing a file using File.write() method.

  • StandardError: throws other errors(enocoding, IO errors) for file write json file

  • Finally, Create a result.json file for successful execution

require 'json'

data = {
   "name" => "John",
   "salary" => 1,
   "department" => "sales",
   "active" =>  true,
   "roles" => [
      "admin",
      "employee",
      "user",
      "visitor"
   ],
   "permanentaddress" => {
      "city" => "Texas",
      "zipcode" => "12345"
   },
   "temporaryaddress" => {
      "city" => "Denver",
      "zipcode" => "84321"
   }
}


begin
  File.write('result.json', JSON.pretty_generate(data))
  puts "Write to JSOn is done."
rescue JSON::GeneratorError
  puts "Generate Error"
rescue Errno::EACCES
  puts "Permission denied for  write to file"
rescue StandardError => e
  puts "Other Error #{e.message}"
end