没有将StringIO隐式转换为String(TypeError)-ruby

时间:2019-01-01 08:08:21

标签: json ruby jekyll

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

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)

请提出更正。

1 个答案:

答案 0 :(得分: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?

&.safe navigation operator,它简化了检查nil并在对象上调用方法的过程。从样式的角度来看,优先使用array.any?而不是!array.empty?

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