JSON::ParserError in … unexpected token at '../../test.json' – RUBY ON RAILS

I’ve been stuck on this for a while now.
I have my JSON (test.json) :

[
{
    "title" : "Star Wars",
    "Durée" : "3h",
    "Date" : "6 Mars",
    "Ratio" : "4.5/5"
},
{
    "title" : "Top Gun",
    "Durée" : "2h",
    "Date" : "17 Mai",
    "Ratio" : "4.3/5"
}]

I have my controller (food_controller.rb) :

class FoodController < ApplicationController

def index

    require "json"
    file = File.join "../../test.json"
    data = JSON.parse(file)
    
end

end

And i have this error :
enter image description here

>Solution :

If your json file is in the root directory of the project then try this:

require "json"

class FoodController < ApplicationController
  def index
    data = JSON.parse(File.read('test.json'))
  end
end

Otherwise if your file is in some directory e.g. tmp then just add this directory name as a prefix to the json file

data = JSON.parse(File.read('tmp/test.json'))

Leave a Reply