Can't flatten JSON array to prepare for CSV conversion using Ruby 2.1.4 -
i have array of nested json "hash" objects need flatten ports on csv cleanly, not nested , "multidimensional" json typically is.
but flatten method (used here ! bang) not working (it creates file no error file empty).
in ruby file below leave working example of commented out code isjust doing conversion without .flatten method. since json array (at highest level) - separated commas , enclosed in square brackets, shouldn't take .flatten method, takes .each in working commented out block? (this docs seems indicate!)
require 'csv' require 'json' # csv.open('false-hotels-merged.csv', 'w') |csv| # json.parse(file.open('monfri-false-hotels-merged.json').read).each |hash| # csv << hash.values # end # end csv.open('wed-all-false-hotels.csv', 'w') |csv| json.parse(file.open('monfri-false-hotels-merged.json').read).flatten! |f| csv << f.values end end
example json data snippet:
[... { "id": "111707", "name": "seven park place william drabble", "phone": "+442073161600", "email": "restaurant@stjameshotelandclub.com", "website": "http://www.stjameshotelandclub.com/michelin-star-chef-william-drabble", "location": { "latitude": 51.5062548, "longitude": -0.1403209, "address": { "line1": "7-8 park place", "line2": "st james's", "line3": "", "postcode": "sw1a 1lp", "city": "london", "country": "uk" } } }, { "id": "104493", "name": "seymour's restaurant & bar", "phone": "+442079352010", "email": "reservations@theleonard.com", "website": "http://www.theleonard.com", "location": { "latitude": 51.51463, "longitude": -0.15779, "address": { "line1": "15 seymour street", "line2": "", "line3": "", "postcode": "w1h 7jw", "city": "london", "country": "uk" } } }, { "id": "250922", "name": "shaka zulu", "phone": "+442033769911", "email": "info@shaka-zulu.com", "website": "http://www.shaka-zulu.com/", "location": { "latitude": 51.5414979, "longitude": -0.1458655, "address": { "line1": "stables market ", "line2": "camden", "line3": "", "postcode": "nw1 8ab", "city": "london", "country": "uk" } } } ]
again, no errors @ in terminal - blank csv file created.
try this:
require 'csv' require 'json' def hflat(h) h.values.flat_map {|v| v.is_a?(hash) ? hflat(v) : v } end csv.open('file.csv', 'w') |csv| json.parse(file.open('file.json').read).each |h| csv << hflat(h) end end
Comments
Post a Comment