user3185039
user3185039

Reputation:

Create JSON from two arrays

I have two arrays say: x=[1,2,3] and y=['a', 'b', 'c']. I want to create a json using x and y arrays in rails console. What is the optimized way to do it. The desired JSON should looks like this:

{
    "obj":
        [
            {
                "key":"a",
                "value": 1
            },
            {
                "key":"b",
                "value": 2
            },
            {
                "key":"c",
                "value": 3
            }
        ]
}

Upvotes: 0

Views: 410

Answers (1)

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121000

x = [1,2,3] and y = ['a', 'b', 'c']
{obj: y.zip(x).map { |k, v| {key: k, value: v} } }

#⇒ {
#  :obj => [
#    {
#        :key => "a",
#      :value => 1
#    },
#    {
#        :key => "b",
#      :value => 2
#    },
#    {
#        :key => "c",
#      :value => 3
#    }
#  ]
# }

If you insist on having string keys:

{ 'obj' => y.zip(x).map { |k, v| { 'key' => k, 'value' => v } } }

To get a json out of the hash, just call to_json on it.

Upvotes: 4

Related Questions