0

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" }

0

2 Answers 2

1

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\"}"
Sign up to request clarification or add additional context in comments.

1 Comment

This is beautiful. The code I posted wasn't exactly the right format but you answered correctly. Thanks for the help!
0
 keys = ["Company", "Address", "City", "State", "ZipCode", "Start", "End"]
 Hash[*keys.zip(sql_result).flatten]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.