【发布时间】:2012-08-28 02:05:44
【问题描述】:
我是 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
【问题讨论】:
-
JSON 是什么样的?您希望 CSV 看起来像什么?
-
刚刚更新了问题伙伴。塔
-
这是一种奇怪的 CSV 格式 - 通常 CSV 会在第一行有键列,在后面的行中有值作为列(因此映射嵌套的 JSON 结构会很混乱)
-
没关系。我对 CSV 格式并不挑剔,只是可以导出到 excel 的东西。是的,JSon 是嵌套的,有点复杂,所以无论是更容易接受所有内容还是有选择地接受我都很好..