Format :json error

Hi I am new to Ruby and Json. Need help with this command being used in
Ruby, for parsing Json files.

I get the following error,

no implicit conversion of Symbol into String (TypeError)
./lib/pages/admin/summary_pg.rb:13:in `format’

This is how its being used,

class summarypage
def get_language_text(language, type, text)

if language.downcase == "french"
  format :json
  fr_file = File.read("/config/data/api/admin/labels_FR.json")
  fr_file_parsed = parse_file(fr_file)
  @text_fr = fr_file_parsed[type][text]
  end
@text_fr

end

def parse_file(language_file)
JSON.parse(language_file)
end
end

require ‘json’ is already included in another environment config file.

if I don’t use the format :json, I get the following error,

undefined method `[]’ for nil:NilClass (NoMethodError)

Appreciate the help. Thanks, Joel

require ‘json’

class SummaryPage
def get_language_text(language, type, text)

if language.downcase == "french"
  format "json"
  fr_file = DATA.read

  fr_file_parsed = parse_file(fr_file)
  @text_fr = fr_file_parsed[type][text]
  puts @text_fr

end

@text_fr

end

def parse_file(language_file)
JSON.parse(language_file)
end
end

SummaryPage.new.get_language_text(‘French’, ‘one’, ‘b’)

END
{
“one”: { “b” : “hello” },
“two”: “goodbye”
}

–output:–
hello

If you change the last line to:

SummaryPage.new.get_language_text('French', 'three', 'b')

then the output is:

1.rb:9:in get_language_text': undefined method[]’ for nil:NilClass
(NoMethodError)
from 1.rb:21:in `’

which comes from:

fr_file_parsed[“three”][“b”]

fr_file_parsed[‘three’] doesn’t exist, and when you try to retrieve a
non-existent key from a Hash, ruby returns nil. So that line is
equivalent to:

 nil["b"]

and you get the error: “undefined method `[]’ for nil:NilClass”

Calling the method Kernel#format does nothing–you don’t use it’s return
value, so it’s discarded. And you get the error:

 no implicit conversion of Symbol into String (TypeError)

because the format() method takes a string as an argument and
not a symbol. It looks like you copied the code from some rails code.

Awesome! Thank you so much!!! that solved my issue.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs