我希望遍历json文件的目录并将其转换为ruby哈希。我的文件循环器功能可以成功捕获每个文件,并且文件格式正确为json。这是我的代码:
def self.update_server
if Dir.exist?("log/order_errors") == true
logger.debug "#{Dir.entries("log/order_errors")}"
Dir.foreach("log/order_errors") { |f|
logger.debug "Retrieved #{f}"
File.open(f, "r") { |current_file|
JSON.parse(current_file)
}
}
else
logger.error "Was unable to find the directory specified."
end
end
对正在进行的工作或整理文件以便正确解析它们需要做什么的任何想法吗?
JSON.parse()
接受字符串作为参数,而不是文件:
require 'json'
File.open('data.json') do |f|
JSON.parse(f)
end
--output:--
...no implicit conversion of File into String (TypeError)...
这是这样做的方法:
require 'json'
File.open('data.json') do |f|
hash = JSON.parse(f.read) #***HERE***
p hash
end
--output:--
{"x"=>1, "y"=>2}
json模块的文档太恐怖了,不幸的是这是ruby的典型。文档说parse()的参数是a JSON document
,这听起来确实更像文件而不是字符串。文档应该说的是,该参数必须是json格式的String。
顺便说一句,在这一行:
if Dir.exist?("log/order_errors") == true
...现存的()方法调用被其返回值替换,因此如果目录存在,ruby会将其转换为:
if true == true
然后,ruby必须进行比较true == true
,然后ruby将比较结果替换为比较结果,即true
产生以下结果:
if true
现在,如果您改为这样写:
if Dir.exist?("log/order_errors")
再次,将exist?()方法调用替换为其返回值,如果目录存在,则将获得以下信息:
if true
如果该目录不存在,则用将替换exist?()方法调用false
,从而产生以下内容:
if false
因此,== true
在exist?()方法调用之后进行写入既浪费了键入时间,又浪费了处理时间,因为它需要使用ruby进行额外的比较。如上所示,无需进行比较即可获得相同的结果。规则是:如果方法返回true或false,则无需在== true
其后编写。在ruby中,通常很容易分辨出方法何时返回true或false,因为该方法名将以?
。结尾。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句