Leem.fin Leem.fin - 1 month ago 5x
Ruby Question

Failed to load file in my ruby code

I wrote a simple Ruby script, which load a json data file. The project folder structure is like this:

-- script.rb
-- data.json

The data.json looks like this:

"company": {
"name": "ABC",
"address": "X street"

The script.rb looks like this:

require 'json'

data = JSON.load(File.read('data.json'))
name = data['company']['name']

When I run my script by command
ruby script.rb
, I get the following error:

script.rb:3:in `read': No such file or directory @ rb_sysopen - data.json (Errno::ENOENT)

Why my ruby script can't find the data.json file to load?


Try parse instead load, because JSON.parse is to read strings.

data = JSON.parse(File.read('data.json'))

for me last time working this:

  file = File.read('./data.json')
  @data = JSON.parse(file)

try read './data.json' instead 'data.json'