【问题标题】:Trouble parsing file obtained from Dir.glob无法解析从 Dir.glob 获得的文件
【发布时间】:2019-11-07 15:03:00
【问题描述】:

我是红宝石新手。尝试使用 JSON.parse() 解析从 Dir.glob 命令获得的文件时出错

require 'json'

Dir.glob('**/*/.json').each do |f| # find all the .json file and loop each file
  puts f
  data = JSON.parse(f)
  if data['Apple'].nil?
    puts "skipping file #{f} as it does not have Apple"
    next
  end
  parsed_key= File.dirname(data['Apple'][0]['red'][0]['key'])
  puts parsed_key
end

`parse': 767: 'xyz/abc/config.json' (JSON::ParserError) 处出现意外标记

【问题讨论】:

  • 问题肯定是文件xyz/abc/config.json包含无效的JSON。请仔细检查并发布该文件的内容。

标签: json ruby parsing


【解决方案1】:

f 只有路径,一个字符串。如果你想要文件的内容,你需要先阅读它,data = JSON.parse(File.read(f))

【讨论】:

  • 我也试过这个,但是我得到了为 nil:NilClass (NoMethodError) 获取 parsed_key 未定义方法 `[]' 的错误
  • 该文件可能包含 'null' 那么在 ruby​​ 中是一个 nil。
猜你喜欢
  • 2015-05-28
  • 2017-09-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多