read a json file in ruby

To read a JSON file in Ruby, you need to use the built-in JSON library. Here are the steps to do it:

  1. Require the json library:
main.rb
require 'json'
15 chars
2 lines
  1. Open the JSON file using File.open:
main.rb
file = File.open('file.json')
30 chars
2 lines
  1. Parse the JSON data using JSON.parse:
main.rb
data = JSON.parse(file.read)
29 chars
2 lines
  1. Close the file:
main.rb
file.close
11 chars
2 lines

Now, the data variable will hold the parsed JSON data, which you can access like any other Ruby data structure.

Here's an example JSON file and Ruby code to demonstrate:

example.json

{
  "name": "John",
  "age": 30,
  "city": "New York"
}
56 chars
6 lines

example.rb

main.rb
require 'json'

file = File.open('example.json')
data = JSON.parse(file.read)
file.close

puts data['name']
puts data['age']
puts data['city']
143 chars
10 lines

Output:

main.rb
John
30
New York
17 chars
4 lines

gistlibby LogSnag