Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot convert Hash to String?

Tags:

ruby

I am trying to parse the JSON response from Wordnik's API. This is built with Sinatra. I keep getting the error "TypeError at /word" "can't convert Hash into String". Am I using the json parser incorrectly?

Here's my code:

get '/word' do
  resp = Wordnik.words.get_random_word(:hasDictionaryDef => 'true', :maxCorpusCount => 20, :minLength => 10)
  result = JSON.parse(resp)
  word = result.word
  return word.to_s
end
like image 918
conbask Avatar asked Dec 14 '11 06:12

conbask


2 Answers

You are probably getting a hash. To convert it use to_json:

JSON.parse(resp.to_json)
like image 62
NARKOZ Avatar answered Sep 24 '22 08:09

NARKOZ


You have not given what's the JSON response that you are parsing. But assuming it is something of the form

{
    "word":"my_word"
}

you need to do result["word"] to get the value after parsing the JSON response.

like image 37
randomuser Avatar answered Sep 25 '22 08:09

randomuser