是否有一个实用程序可以帮助我重新格式化Rails,JS或Ruby中的JSON结构?
我正在使用原始sql调用遗留数据库。 sql_result = ActiveRecord :: Base.connection.execute(sql) 渲染json:sql_result,root:false
数据返回正常,但我需要重新格式化此JSON输出... [" MyBiz,LLC", " 55 Main St"," San Francisco"," CA"," 94103", &#34 3/06/2007"&#34 12/31/2007"]
看起来像这样...... { "公司":" MyBiz,LLC", "地址":" 55 Main St", " City":" San Francisco", "状态":" CA&#34 ;, "邮编":" 94103&#34 ;, "开始":" 03/06/2007&#34 ;, "末端":" 12 /二千零七分之三十一" }
答案 0 :(得分:1)
字段名称丢失了。尝试类似:
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\"}"
答案 1 :(得分:0)
keys = ["Company", "Address", "City", "State", "ZipCode", "Start", "End"]
Hash[*keys.zip(sql_result).flatten]