Qiang Blog

Just another zhangjingqiang's blog.

How to bulk make json list with ruby?

File example:

# text_list
text1
text2
text3

Ruby batch:

#!/usr/bin/ruby

require 'json'

class Maker
  def initialize(counter=0)
    @counter = counter
    case counter
    when 0
      @position = 'bottom-center'
      @type = 'horizontal'
    when 1
      @position = 'vertical-right'
      @type = 'vertical'
    end
  end

  def read_write
    File.open('text_list', 'r') do |fr|
      while(line = fr.gets)
        json = json_format(line.strip, @counter)
        @counter = @counter + 1
        p JSON.generate(json)
        File.open('new_json', 'a') { |fw| fw.write(JSON.generate(json).to_s + ',') }
      end
    end
  end

  def json_format(line, counter)
    {
      "id":"#{counter}",
      "position": "#{@position}",
      "type": "#{@type}",
      "text":"#{line}"
    }
  end
end

if ARGV.empty?
  p 'Input a value, please.'
  p 'For example:'
  p 'Horizontal -- ruby mjl.rb 0'
  p 'Vertical -- ruby mjl.rb 1'
  exit
end

if ARGV.length > 1
  p 'Please input one value only.'
  exit
end

if not [0, 1].include?(ARGV[0].to_i)
  p 'Please input 0 or 1'
  exit
end

m = Maker.new ARGV[0].to_i
m.read_write

Then use https://jsonformatter.curiousconcept.com format the json list.

json ruby