Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

no implicit conversion of StringIO into String (TypeError) - ruby

Tags:

json

ruby

jekyll

I have a script called import.rb which will import json content from url to drafts directory in jekyll. Below is my code.

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

When I run ruby _scripts/import.rb I get error like

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)

Please suggest the corrections.

like image 994
Fun Media Avatar asked Sep 06 '25 03:09

Fun Media


1 Answers

Change this:

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

To this:

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

The .string method Returns underlying String object.

And while you're at it, change this:

array && !array.empty?

To this:

array&.any?

&. is the safe navigation operator and it simplifies the process of checking for nil and calling a method on the object. And from a style perspective, it's preferred to call array.any? over !array.empty?.

Finally, when using FileUtils.mkdir_p you do not have to include the guard condition unless Dir.exist?(drafts_dir). It can be safely called without concern that it will remove or overwrite the existing directory.

like image 141
anothermh Avatar answered Sep 07 '25 21:09

anothermh