Chucks
Chucks

Reputation: 899

hash to json with out nested arrays in json

I am generating a hash out of three arrays and next trying to construct a json. I succeeded by json object has array.

require 'json'
A = [['A1', 'A2', 'A3'], [ "A1_xfactor", "A2_xfactor", "A3_xfactor"], ["A1_pull", "A2_pull", "A3_pull"]]

kl = { 'obj' => A[0].zip(A[1],A[2]).map { |k, v,l|  { 'f1' => k, 'f2' => v, 'xfactor' => l} }}.to_json


puts kl

Output

  {
    "obj": [{
        "f1": "A1",
        "f2": "A1_xfactor",
        "xfactor": "A1_pull"
    }, {
        "f1": "A2",
        "f2": "A2_xfactor",
        "xfactor": "A2_pull"
    }, {
        "f1": "A3",
        "f2": "A3_xfactor",
        "xfactor": "A3_pull"
    }]
}

Instead of array, I would like have it without an array and F1 has to come out as a separate object.

{
    "obj": {
        "A1": {
            "f2": "A1_xfactor",
            "xfactor": "A1_pull"
        },
        "A2": {
            "f2": "A2_xfactor",
            "xfactor": "A2_pull"
        },
        "A3": {
            "f2": "A3_xfactor",
            "xfactor": "A3_pull"
        }
    }
}

Upvotes: 3

Views: 78

Answers (1)

Sebastián Palma
Sebastián Palma

Reputation: 33471

You can try reducing A by zipping each of its elements.

Then iterate over each array of arrays using each_with_object, for each element, yield its first element as key, the second as f2 and the second/last element within the array as factor.

Assign the custom hash to the key (A1, A2, A3).

After that you can store it and use like { obj: result }.

A.reduce(&:zip).each_with_object({}) do |((key, f2), factor), hash|
  hash[key] = { f2: f2, xfactor: factor }
end
# {"A1"=>{:f2=>"A1_xfactor", :xfactor=>"A1_pull"},
#  "A2"=>{:f2=>"A2_xfactor", :xfactor=>"A2_pull"},
#  "A3"=>{:f2=>"A3_xfactor", :xfactor=>"A3_pull"}}

Upvotes: 4

Related Questions