2012-08-28 46 views
0

我是Ruby新手,並且有問題。我正在嘗試創建一個將JSON轉換爲CSV的.rb文件。通過FasterCSV將JSON轉換爲CSV

我跨了一些不同來源來到我做:

require "rubygems" 
require 'fastercsv' 
require 'json' 

csv_string = FasterCSV.generate({}) do |csv| 
    JSON.parse(File.open("small.json").read).each do |hash| 
    csv << hash 
    end 
end 

puts csv_string 

現在,它實際上是輸出文本,但他們都擠成一團沒有空格,逗號等我如何使它更加個性化,爲CSV文件清除,以便我可以導出該文件?

的JSON看起來像:

 { 
      "results": [ 
       { 
        "reportingId": "s", 
        "listingType": "Business", 
        "hasExposureProducts": false, 
        "name": "Medeco Medical Centre World Square", 
        "primaryAddress": { 
         "geoCodeGranularity": "PROPERTY", 
         "addressLine": "Shop 9.01 World Sq Shopng Cntr 644 George St", 
         "longitude": "151.206172", 
         "suburb": "Sydney", 
         "state": "NSW", 
         "postcode": "2000", 
         "latitude": "-33.876416", 
         "type": "VANITY" 
        }, 

        "primaryContacts": [ 
         { 
          "type": "PHONE", 
          "value": "(02) 9264 8500" 
         } 
        ] 
       },xxx 
     } 

的CSV只是有類似:

 reportingId, s, listingType, Business, name, Medeco Medical...., addressLine, xxxxx, longitude, xxxx, latitude, xxxx, state, NSW, postcode, 2000, type, phone, value, (02) 92648544    
+1

JSON的外觀如何?你想讓CSV看起來像什麼? –

+0

剛更新問題隊友。 Ta – Doz

+0

這是一種奇怪的CSV格式 - 通常CSV在第一行中有鍵列,在後面的行中有列值(因此映射嵌套的JSON結構會變得很混亂) –

回答

2

由於您的JSON結構是散列和列表的組合,也有不同的層次高度,它不像你展示的代碼那樣微不足道。然而(假設你的輸入文件總是看起來一樣),編寫一個合適的轉換器應該不難。在最低水平,可以通過

hash.to_a.flatten 

例如變換哈希CSV

input = JSON.parse(File.open("small_file.json").read) 
writer = FasterCSV.open("out.csv", "w") 
writer << input["results"][0]["primaryAddress"].to_a.flatten 

會給你

type,VANITY,latitude,-33.876416,postcode,2000,state,NSW,suburb,Sydney,longitude,151.206172,addressLine,Shop 9.01 World Sq Shopng Cntr 644 George St,geoCodeGranularity,PROPERTY 

希望,指導您的方向。

順便說一句,你的JSON看起來無效。您應該將},xxx行更改爲}]

+0

謝謝是的,我知道它的無效,但它的東西來自我的控制服務器,但我應該看看做我自己的那個。謝謝 – Doz

+0

只有問題我有沒有一個空間之間的價值,然後下一個關鍵......基於我有什麼,你如何添加額外的空間? – Doz