【发布时间】:2018-07-30 14:51:47
【问题描述】:
我正在将此方法的结果保存到 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 的输出: {"12":{"id":"12","title":"如何让它工作?","description":"不知道..."},"14":{"id":" 14","title":"Yoga","description":"Guide"}}
更新 3
现在我已经用video_hash = Hash[*hash_to_return.flatten] 覆盖了这种情况并获得了所需的格式。
所以回到家里,我会尝试运行普通的 ruby 文件(正如 rwold 所说),我也会测试 ahmed eshra 的方法。
衷心感谢所有参与的人!
更新 4
我尝试将我的代码作为 Rails 外部的普通 ruby 文件(稍作修改),它运行良好!
【问题讨论】:
-
getting_hash在哪里使用? -
@apneadiving 类视频控制器
-
我确认:存储的是 ruby 哈希,而不是 json。不知道为什么,它是正确的文件吗?真的是要json调用吗?
-
File.read("foo.json")=>"{\"12\":{\"id\":\"12\",\"title\":\"How to make it work?\",\"description\":\"No idea...\"},\"14\":{\"id\":\"14\",\"title\":\"Yoga\",\"description\":\"Guide\"}}"和JSON.parse(File.read("foo.json"))=>{"12"=>{"id"=>"12", "title"=>"How to make it work?", "description"=>"No idea..."}, "14"=>{"id"=>"14", "title"=>"Yoga", "description"=>"Guide"}} -
我刚试过你的代码,包括文件 IO,效果很好。您提供给我们的示例输入 (
test) 与您的代码实际生成的内容之间存在细微差别,或者您的堆栈中存在已在更高版本中修复的错误(我使用的是 Rails 5.1,ruby 2.4.0;json 1.8.3)。您可能会发现分享您正在使用的版本很有帮助。
标签: ruby-on-rails json ruby hash