1

Having collected some JSON from a file using the Curb gem, I assign a portion of it to an instance variable:

self.json_stuff = {"title" => json["title"], "description" => json["description"], "image" => json["image"]}.to_json

This then gets stored in the database as JSON:

serialize :json_stuff, JSON
...
self.save

Later on I check for the presence of said json_stuff:

return self.json_stuff.present?

And get the following error:

TypeError - no implicit conversion of Hash into String:
  json (1.8.3) lib/json/common.rb:155:in `initialize'
  json (1.8.3) lib/json/common.rb:155:in `new'
  json (1.8.3) lib/json/common.rb:155:in `parse'

I've stepped through the code and I know that the collection of the JSON from the file is done without issue.

6
  • Could you give use more information please, first of all what does p self.json_stuffprints ? Furthermore, I think you try to encode your object two times, the first one with .to_json which give you a string, and then when you save id with the serialize action, could you try to remove .to_json from your first line ? Commented Aug 24, 2015 at 15:05
  • when I try to inspect the variable in the rails console I get the same error : no implicit conversion of Hash into String... I'll look in to the suggestion of it being encoded twice... Thanks for the pointer... Commented Aug 24, 2015 at 15:09
  • ...tried removing to_json but still getting the same error... When I get the json from the file, I parse it using JSON.parse, is this correct? Commented Aug 24, 2015 at 15:17
  • We can't guess, you need to give us some code you wrote Commented Aug 24, 2015 at 15:19
  • I didn't mean have I used JSON.parse correctly, I mean was I right to use JSON.parse at all? Commented Aug 24, 2015 at 15:20

1 Answer 1

1

As far as I know, the present? method is for Strings to check if they are not empty. If you just want to return boolean based on the existence of json_stuff you should check if it is nil for example with

return self.json_stuff.nil?

The type of self.json_stuff is Hash instead of String.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.