将哈希保存为json并将其恢复到ruby on rails上的麻烦

时间:2018-02-20 09:34:44

标签: ruby-on-rails json ruby hash

我将此方法的结果保存为json格式的文件:

class VideosController < ApplicationController
    ...

    def getting_hash
        video = Video.new
        video.id = 12
        video.title = "How to make it work?"
        video.desc = "No idea..."
        video_hash = Hash.new
        video_hash[video.id] = {id: video.id, title: video.title, desc: video.desc}
        write_to_file(video_hash)
    end

    ...
end

因此,为了保存到我使用的文件:

  def write_to_file(model)
    path  = "#{Rails.root}/public/my_file.cache"
    open(path, 'w') { |f|
      f.write(model.to_json)
    }
  end

看起来像香草,但当我使用时:      read_from_file(my_file.cache)

  def read_from_file(file_name)
    path = Rails.root + "public/#{file_name}"
    file = File.read(path)
    hash_to_return = JSON.parse(file)
  end

它不返回哈希值,而是返回数组!

NoMethodError (undefined method `id' for #<Array:0x007f1926325460>):

当我检查时:

["12", {"id"=>"12", "title"=>"How to make it work?", "description"=>"No idea..."}]

我不明白这是怎么可能的,因为如果我使用变量,它会让一切变得完美:

(byebug) test = {"12":{"id":12,"title":"How to make it work?","desc":"No idea..."}}
{:"12"=>{:id=>12, :title=>"How to make it work?", :desc=>"No idea..."}}
(byebug) test2 = test.to_json
"{\"12\":{\"id\":12,\"title\":\"How to make it work?\",\"desc\":\"No idea...\"}}"
(byebug) JSON.parse(test2)
{"12"=>{"id"=>12, "title"=>"How to make it work?", "desc"=>"No idea..."}}

请帮助我获得正确的哈希值!任何想法都非常感谢!

更新

JSON::ParserError (lexical error: invalid char in json text.
                         {"12"=>{:id=>"12", :title=>
                     (right here) ------^
):

更新2 my_file.cache的输出: {&#34; 12&#34;:{&#34; id&#34;:&#34; 12&#34;,&#34; title&#34;:&#34;如何使其发挥作用?&# 34;,&#34;描述&#34;:&#34;不知道......&#34;},&#34; 14&#34;:{&#34; id&#34;:&#34; 14&#34;&#34;标题&#34;:&#34;瑜伽&#34;&#34;描述&#34;:&#34;向导及#34;}}

更新3 现在,我已用video_hash = Hash[*hash_to_return.flatten]覆盖了这种情况并获得了所需的格式。 所以回到家里,我将尝试运行普通的ruby文件(如rwold所说),并且我还将测试ahmed eshra的方法。 真诚地感谢所有参与者!

更新4

我尝试将我的代码作为Rails之外的普通ruby文件(稍作修改),它完美无缺!

1 个答案:

答案 0 :(得分:1)

我认为使用to_json转换传递对象本身,对于你需要的东西更好,它将被保存为哈希。

def getting_hash
    video = Video.new
    video.id = 12
    video.title = "How to make it work?"
    video.desc = "No idea..."
    # Removing the hash conversion step
    write_to_file(video)
end