Skip to content

Welcome to Tech by Example

Menu
  • Home
  • Posts
  • System Design Questions
Menu

JSON parse a file or string in Ruby Language

Posted on August 7, 2021August 7, 2021 by admin

Overview

json module of ruby can be used a JSON parse a file or string in ruby language

https://ruby-doc.org/stdlib-2.6.3/libdoc/json/rdoc/JSON.html

It provides a parse function that can be used to parse a file.

Parse a string

Below is the program for the same.

require 'json'
parsed = JSON.parse('{"a":"x","b":"y"}')
puts parsed
puts parsed["a"]
puts parsed["b"]

Output

{"a"=>"x", "b"=>"y"}
x
y

Parse a file

Create a file named temp.json with below content

{"a":"x","b":"y"}

Now run the below program

require 'json'
file = File.read('temp.json')
parsed = JSON.parse(file)

puts parsed
puts parsed["a"]
puts parsed["b"]

Output

{"a"=>"x", "b"=>"y"}
x
y
  • ruby
  • ©2025 Welcome to Tech by Example | Design: Newspaperly WordPress Theme