无法使用Ruby 2.1.4压缩JSON数组以准备CSV转换

时间:2015-07-22 14:56:16

标签: arrays ruby json csv

我有一个嵌套的JSON“哈希”对象数组,我需要将它完全展平,以便它干净地移植到CSV,这显然不是嵌套的,而且通常是像JSON那样的“多维”。

但是flatten方法(在这里使用!bang)不起作用(它创建的文件没有错误,但文件是空的)。

在下面的ruby文件中,我留下了一个注释掉代码的工作示例,它只是在没有.flatten方法的情况下进行简单转换。由于JSON是一个数组(在最高级别) - 用逗号分隔并用方括号括起来,不应该采用.flatten方法,就像它在工作注释掉的块中一样。 (这也是文档似乎表明的内容!)

require 'csv'
require 'json'

# CSV.open('false-hotels-merged.csv', 'w') do |csv|
#   JSON.parse(File.open('monfri-false-hotels-merged.json').read).each do |hash|
#     csv << hash.values
#   end
# end

CSV.open('wed-all-false-hotels.csv', 'w') do |csv|
  JSON.parse(File.open('monfri-false-hotels-merged.json').read).flatten! do |f|
    csv << f.values
  end
end

示例JSON数据片段:

[...
        {
          "id": "111707",
          "name": "Seven Park Place by William Drabble",
          "phone": "+442073161600",
          "email": "restaurant@stjameshotelandclub.com",
          "website": "http://www.stjameshotelandclub.com/michelin-star-chef-william-drabble",
          "location": {
            "latitude": 51.5062548,
            "longitude": -0.1403209,
            "address": {
              "line1": "7-8 Park Place",
              "line2": "St James's",
              "line3": "",
              "postcode": "SW1A 1LP",
              "city": "London",
              "country": "UK"
            }
          }
        },
        {
          "id": "104493",
          "name": "Seymour's Restaurant & Bar",
          "phone": "+442079352010",
          "email": "reservations@theleonard.com",
          "website": "http://www.theleonard.com",
          "location": {
            "latitude": 51.51463,
            "longitude": -0.15779,
            "address": {
              "line1": "15 Seymour Street",
              "line2": "",
              "line3": "",
              "postcode": "W1H 7JW",
              "city": "London",
              "country": "UK"
            }
          }
        },
        {
          "id": "250922",
          "name": "Shaka Zulu",
          "phone": "+442033769911",
          "email": "info@shaka-zulu.com",
          "website": "http://www.shaka-zulu.com/",
          "location": {
            "latitude": 51.5414979,
            "longitude": -0.1458655,
            "address": {
              "line1": "Stables Market ",
              "line2": "Camden",
              "line3": "",
              "postcode": "NW1 8AB",
              "city": "London",
              "country": "UK"
            }
          }
        }
    ]

同样,终端中根本没有错误 - 只创建空白CSV文件。

2 个答案:

答案 0 :(得分:3)

Array#flatten只会使数组变平。还有Hash#flatten,它也产生一个数组。你似乎想要展平一个我不知道库方法的嵌套Hash。

您的结果似乎是空的,因为在.each之后缺少flatten - 该块根本就没有运行。

答案 1 :(得分:1)

试试这个:

require 'csv'
require 'json'

def hflat(h)
  h.values.flat_map {|v| v.is_a?(Hash) ? hflat(v) : v }
end

CSV.open('file.csv', 'w') do |csv|
  JSON.parse(File.open('file.json').read).each do |h| 
    csv << hflat(h)
  end
end