我試圖通過對客戶資料(姓名和電子郵件)的JSON響應解析和結構,相同的列標題的CSV文件。紅寶石 - FasterCSV後解析JSON
出於某種原因,我每次運行該代碼時,我得到一個CSV所有的第一名稱的列表中一個單元文件(名稱中帶有之間沒有分離...只是附加到對方的名字的字符串)和姓氏相同的東西。以下代碼不包括添加電子郵件(稍後我會擔心)。
代碼:
def self.fetch_emails
access_token ||= AssistlyArticle.remote_setup
cust_response = access_token.get("https://blah.desk.com/api/v1/customers.json")
cust_ids = JSON.parse(cust_response.body)["results"].map{|w| w["customer"]["id"].to_i}
FasterCSV.open("/Users/default/file.csv", "wb") do |csv|
# header row
csv << ["First name", "Last Name"]
# data rows
cust_ids.each do |cust_firstname|
json = JSON.parse(cust_response.body)["results"]
csv << [json.map{|x| x["customer"]["first_name"]}, json.map{|x| x["customer"]["last_name"]}]
end
end
end
輸出:
First Name | Last Name
JohnJillJamesBill SearsStevensSethBing
等等...
所需的輸出:
First Name | Last Name
John | Sears
Jill | Stevens
James | Seth
Bill | Bing
樣品JSON:
{
"page":1,
"count":20,
"total":541,
"results":
[
{
"customer":
{
"custom_test":null,
"addresses":
[
{
"address":
{
"region":"NY",
"city":"Commack",
"location":"67 Harned Road,
Commack,
NY 11725,
USA",
"created_at":"2009-12-22T16:21:23-05:00",
"street_2":null,
"country":"US",
"updated_at":"2009-12-22T16:32:37-05:00",
"postalcode":"11725",
"street":"67 Harned Road",
"lng":"-73.196225",
"customer_contact_type":"home",
"lat":"40.716894"
}
}
],
"phones":
[
],
"last_name":"Suriel",
"custom_order":"4",
"first_name":"Jeremy",
"custom_t2":"",
"custom_i":"",
"custom_t3":null,
"custom_t":"",
"emails":
[
{
"email":
{
"verified_at":"2009-11-27T21:41:11-05:00",
"created_at":"2009-11-27T21:40:55-05:00",
"updated_at":"2009-11-27T21:41:11-05:00",
"customer_contact_type":"home",
"email":"[email protected]"
}
}
],
"id":8,
"twitters":
[
{
"twitter":
{
"profile_image_url":"http://a3.twimg.com...",
"created_at":"2009-11-25T10:35:56-05:00",
"updated_at":"2010-05-29T22:41:55-04:00",
"twitter_user_id":12267802,
"followers_count":93,
"verified":false,
"login":"jrmey"
}
}
]
}
},
{
"customer":
{
"custom_test":null,
"addresses":
[
],
"phones":
[
],
"last_name":"",
"custom_order":null,
"first_name":"[email protected]",
"custom_t2":null,
"custom_i":null,
"custom_t3":null,
"custom_t":null,
"emails":
[
{
"email":
{
"verified_at":null,
"created_at":"2009-12-05T20:39:00-05:00",
"updated_at":"2009-12-05T20:39:00-05:00",
"customer_contact_type":"home",
"email":"[email protected]"
}
}
],
"id":27,
"twitters":
[
null
]
}
}
]
}
是否有更好的使用FasterCSV的允許這樣做?我認爲< <將每次添加到一個新的行...但它似乎並不奏效。我將不勝感激任何幫助!
你忘了我們展示了JSON的樣品。如果您提供的鏈接死亡,那麼對於尋找解決類似問題的人來說,這個問題將毫無價值。另外,你迫使任何想幫助你的人去挖掘它,然後發現它是一個虛假的請求。 –
你說得對。我的錯。我已經添加了JSON的樣本。謝謝你的提示。 – ns1
你使用的是什麼版本的ruby? – PriteshJ