Moamen Naanou
Moamen Naanou

Reputation: 1713

How to combine multiple arrays into single JSON object

I have three arrays:

c = ["1", "2", "3"]
d = [["x1","x2","x3"],["x4","x5","x6"], ["x7","x8","x9"]]
e = [["20","21","22"], ["23","24","25"], ["26","27","28"]]

And I want to merge them together in Ruby to get this JSON result:

[
 {"1":{ 
        "x1":"20",
        "x2":"21",
        "x3":"22"
      },
      { 
        "x4":"23",
        "x5":"24",
        "x6":"25"
      },
      { 
        "x7":"26",
        "x8":"27",
        "x9":"28"
      },
 }
]

Upvotes: 0

Views: 390

Answers (1)

Cary Swoveland
Cary Swoveland

Reputation: 110675

c = ["1", "2", "3"]
d = [['x1','x2','x3'],['x4','x5','x6'], ['x7','x8','x9']]
e = [[20,21,22], [23,24,25], [26,27,28]]

require 'json'

pairs = d.map { |a| a.map(&:to_sym) }.zip(e).map(&:transpose)
  #=> [[[:x1, 20], [:x2, 21], [:x3, 22]],
  #    [[:x4, 23], [:x5, 24], [:x6, 25]],
  #    [[:x7, 26], [:x8, 27], [:x9, 28]]]    
c.each_with_object({}) { |s,h| h[s] = pairs.shift.to_h }.to_json
  #=> "{\"1\":{\"x1\":20,\"x2\":21,\"x3\":22},\"2\":
       {\"x4\":23,\"x5\":24,\"x6\":25},\"3\":{\"x7\":26,\"x8\":27,\"x9\":28}}" 

(I broke the JSON string to two lines to avoid the need for horizontal scrolling.)

Alternatively,

pairs = [d.map { |a| a.map(&:to_sym) }, e].transpose.map(&:transpose)

Upvotes: 4

Related Questions