简体   繁体   English

Rails序列化JSON->没有将Hash隐式转换为String

[英]Rails Serialized JSON -> no implicit conversion of Hash into String

Having collected some JSON from a file using the Curb gem, I assign a portion of it to an instance variable: 使用Curb gem从文件中收集了一些JSON之后,我将其中的一部分分配给实例变量:

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

This then gets stored in the database as JSON: 然后将其作为JSON存储在数据库中:

serialize :json_stuff, JSON
...
self.save

Later on I check for the presence of said json_stuff : 稍后我检查是否存在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. 我已经遍历了代码,并且知道从文件中收集JSON不会出现问题。

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 如果您只想根据json_stuff的存在返回布尔值,则应检查它是否为nil ,例如

return self.json_stuff.nil?

The type of self.json_stuff is Hash instead of String . self.json_stuff的类型是Hash而不是String

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM