Reputation: 99
Is there a utility that will help me reformat JSON structure in Rails, JS or Ruby?
I'm making a call to a legacy db with raw sql. sql_result = ActiveRecord::Base.connection.execute(sql) render json: sql_result, root:false
Data returns fine but I need to reformat this JSON output... ["MyBiz, LLC", "55 Main St","San Francisco","CA","94103", "3/06/2007","12/31/2007"]
To look like this... { "Company":"MyBiz, LLC", "Address":"55 Main St", "City":"San Francisco", "State":"CA", "ZipCode":"94103", "Start":"03/06/2007", "End":"12/31/2007" }
Upvotes: 0
Views: 240
Reputation: 308
keys = ["Company", "Address", "City", "State", "ZipCode", "Start", "End"]
Hash[*keys.zip(sql_result).flatten]
Upvotes: 0
Reputation: 9344
The field names were lost. Try something like:
keys = ["Company", "Address", "City", "State", "ZipCode", "Start", "End"]
["MyBiz, LLC", "55 Main St","San Francisco","CA","94103", "3/06/2007","12/31/2007"].
each_with_index.map { |v, i| { keys[i] => v } }.reduce(:merge).to_json
# => "{\"Company\":\"MyBiz, LLC\",\"Address\":\"55 Main St\",\"City\":\"San Francisco\",\"State\":\"CA\",\"ZipCode\":\"94103\",\"Start\":\"3/06/2007\",\"End\":\"12/31/2007\"}"
Upvotes: 1