0

Rubyは初めてで、質問がありました。JSONをCSVに変換する.rbファイルを作成しようとしています。

私は私を作らせたいくつかの異なる情報源に出くわしました:

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             
4

1 に答える 1

3

JSON 構造はハッシュとリストの混合であり、さまざまな高さのレベルもあるため、表示するコードほど単純ではありません。ただし (入力ファイルが常に同じように見えると仮定すると)、適切なコンバーターを作成するのは難しくありません。最下位レベルでは、次の方法でハッシュを CSV に変換できます。

hash.to_a.flatten

例えば

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行を に変更する必要があります}]

于 2012-08-31T10:48:18.653 に答える