我是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
JSON的外观如何?你想让CSV看起来像什么? –
刚更新问题队友。 Ta – Doz
这是一种奇怪的CSV格式 - 通常CSV在第一行中有键列,在后面的行中有列值(因此映射嵌套的JSON结构会变得很混乱) –