【问题标题】:no implicit conversion of StringIO into String (TypeError) - ruby没有将 StringIO 隐式转换为 String (TypeError) - ruby
【发布时间】:2019-01-01 08:08:21
【问题描述】:

我有一个名为 import.rb 的脚本,它将 json 内容从 url 导入到 jekyll 中的草稿目录。下面是我的代码。

require 'fileutils'
require 'json'
require 'open-uri'

# Load JSON data from source
# (Assuming the data source is a json file on your file system)
data = JSON.parse(open('https://script.google.com/macros/s/AKfycbyHFt1Yz96q91-D6eP4uWtRCcF_lzG2WM-sjrpZIr3s02HrICBQ/exec'))

# Proceed to create post files if the value array is not empty
array = data["user"]
if array && !array.empty?
  # create the `_drafts` directory if it doesn't exist already
  drafts_dir = File.expand_path('./_drafts', __dir__)
  FileUtils.mkdir_p(drafts_dir) unless Dir.exist?(drafts_dir)

  # iterate through the array and generate draft-files for each entry
  # where entry.first will be the "content" and entry.last the "title"
  array.each do |entry|
    File.open(File.join(drafts_dir, entry.last), 'wb') do |draft|
      draft.puts("---\n---\n\n#{entry.first}")
    end
  end
end

当我运行 ruby _scripts/import.rb 时,我会收到类似

的错误
3: from _scripts/import.rb:7:in `<main>'
    2: from /usr/lib/ruby/2.5.0/json/common.rb:156:in `parse'
    1: from /usr/lib/ruby/2.5.0/json/common.rb:156:in `new'
    /usr/lib/ruby/2.5.0/json/common.rb:156:in `initialize': no implicit conversion of StringIO into String (TypeError)

请提出更正建议。

【问题讨论】:

    标签: json ruby jekyll


    【解决方案1】:

    改变这个:

    data = JSON.parse(open('https://script.google.com/macros/s/AKfycbyHFt1Yz96q91-D6eP4uWtRCcF_lzG2WM-sjrpZIr3s02HrICBQ/exec'))
    

    到这里:

    data = JSON.parse(open('https://script.google.com/macros/s/AKfycbyHFt1Yz96q91-D6eP4uWtRCcF_lzG2WM-sjrpZIr3s02HrICBQ/exec').string)
    

    .string 方法Returns underlying String object

    当你这样做的时候,改变这个:

    array && !array.empty?
    

    到这里:

    array&.any?
    

    &amp;.safe navigation operator,它简化了检查nil 和调用对象方法的过程。从风格的角度来看,最好调用array.any? 而不是!array.empty?

    最后,当使用FileUtils.mkdir_p 时,您不必包含保护条件unless Dir.exist?(drafts_dir)。可以安全地调用它,而不必担心它会删除或覆盖现有目录。

    【讨论】:

    • 谢谢,现在我收到类似2: from _scripts/import.rb:18:in `&lt;main&gt;' 1: from _scripts/import.rb:18:in `each' _scripts/import.rb:19:in `block in &lt;main&gt;': undefined method `last' for #&lt;Hash:0x00005600277297a0&gt; (NoMethodError)的错误
    • 我假设您正在尝试读取哈希中 name 键的值(URL 类似于 https://www.flipkart.com/...)。在这种情况下,将entry.last 更改为entry['name']entry.fetch('name')
    • 谢谢,现在错误就像No such file or directory @ rb_sysopen - /home/_scripts/_drafts/https://www.flipkart.com/redmi-note-6-pro-black-64-gb/p/itmfayzxqnzjhtbh?affid=xxx,[Flipkart] Redmi Note 6 Pro (Black, 64 GB)  (4 GB RAM) (Errno::ENOENT)
    • 通过删除entry['name']中的链接来修复它
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-26
    相关资源
    最近更新 更多