2012-08-28 48 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