JSON 到 CSV,跳过某些列并重新排序其他列 - Ruby



我有一个工作脚本,可以很好地将 JSON 文件转换为 CSV 文件,但是我正在尝试编辑脚本以在保存之前对 CSV 文件进行一些更改,目前没有任何成功。

这是我当前的转换脚本:

require 'csv'
require 'json'
require 'set'
def get_recursive_keys(hash, nested_key=nil)
  hash.each_with_object([]) do |(k,v),keys|
    k = "#{nested_key}.#{k}" unless nested_key.nil?
      if v.is_a? Hash
      keys.concat(get_recursive_keys(v, k))
    else
      keys << k
    end
  end
end
json = JSON.parse(File.open(ARGV[0]).read)
headings = Set.new
json.each do |hash|
  headings.merge(get_recursive_keys(hash))
end
headings = headings.to_a
CSV.open(ARGV[0] + '.csv', 'w') do |csv|
  csv << headings
  json.each do |hash|
    row = headings.map do |h|
      v = hash.dig(*h.split('.'))
      v.is_a?(Array) ? v.join(',') : v
    end
    csv << row
  end
end

我用这个命令运行:

for file in directory/*; do ruby json-to-csv.rb "$file"; done

如何编辑此脚本以:

  • 删除带有某些标题的列,例如"分数"和"original_name">
  • (将其余列按从左到右的字母顺序重新排序( - 如果可能的话?

到目前为止,我尝试的所有内容都完全破坏了脚本 - 开始进行这些更改的最佳位置在哪里?

以下是有效的代码:

require 'csv'
require 'json'
require 'set'
def get_recursive_keys(hash, nested_key=nil)
  hash.each_with_object([]) do |(k,v),keys|
    # Col filter
    next if ["score", "original_name"].include? k
    k = "#{nested_key}.#{k}" unless nested_key.nil?
    if v.is_a? Hash
      keys.concat(get_recursive_keys(v, k))
    else
      keys << k
    end
  end
end
json = JSON.parse(File.open(ARGV[0]).read)
headings = Set.new
headings = get_recursive_keys(json)
headings = headings.to_a
# Header sorting
headings = headings.sort { |a, b| a <=> b }

CSV.open(ARGV[0] + '.csv', 'w') do |csv|
  csv << headings
  row = headings.map do |h|
    v = (h.split('.').length > 1) ? json.dig(*h.split('.')) : h
    v.is_a?(Array) ? v.join(',') : v
  end
  csv << row
end

我用这个小的 json 字符串进行了测试: {"score": "12", "name": "Obi", "original_name": "Wan Kenobi", "something": {"sub_key": "芜湖"} }

最新更新