고객 데이터 (이름 및 전자 메일)에 대한 JSON 응답을 구문 분석하고 동일한 열 머리글을 사용하여 CSV 파일을 구성하려고합니다.Ruby - JSON 구문 분석 후 빠른 CSV
어떤 이유로이 코드를 실행할 때마다 하나의 셀에있는 모든 첫 번째 이름의 목록이있는 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
어떤 버전의 루비를 사용하고 있습니까? – PriteshJ